1. 父组件使用props向子组件传递数据
/*父组件代码/
<template>
<div>
<headerDiv :name='nameCent'></headerDiv>
</div>
</template>
<script>
import HeaderDiv form './componets/header'
export default {
data(){
return{
nameCent:'张小龙'
}
},
componets{
headerDiv
}
}
</script>
/*子组件代码/
<template>
<div>
<h5>{{name}}</h5>
</div>
</template>
<script>
export default {
name:'headerDiv',
data(){
return{
flag:null
}
},
props:['name']
}
</script>
2. 子组件使用$emit向父组件传递数据
/*父组件代码/
<template>
<div>
<loginDiv @transferUser='getUser'></loginDiv>
<p>应户名{{username}}</p>
</div>
</template>
<script>
import loginDiv form './componets/login'
export default {
data(){
return{
user:''
}
},
methods:{
getUser(msg){
this.user = msg;
},
}
componets{
loginDiv
}
}
</script>
/*子组件代码/
<template>
<div>
<input v-model='username' @change='setUser' / >
</div>
</template>
<script>
export default {
name:'login',
data(){
return{
username:''
}
},
methods:{
setUser(){
this.$emit('transferUser',this.username);
},
}
}
</script>
网友评论