使用vue有段时间了,今天抽空记录一下父子组件之间的相互传值。
1.父==>子
首先在父组件中引用子组件,并给子组件绑定相应要传的值
<template>
<div class="parent">
<h2>{{ msg }}</h2>
<son :psMsg="zhi" ></son> <!-- 子组件绑定psMsg变量-->
</div>
</template>
<script>
import son from './Son' //引入子组件
export default {
name: 'HelloWorld',
data () {
return {
msg: '父组件',
zhi:'传的值',
username:''
}
},
components:{son},
}
</script>
然后在子组件中准备接收:使用props,然后直接用就行了
<template>
<div class="son">
<p>{{ sonMsg }}</p>
<p>子组件接收到内容:{{ psMsg }}</p>
</div>
</template>
<script>
export default {
name: "son",
props:['psMsg'],//接收psMsg值
data(){
return {
sonMsg:'子组件',
user:'子传父的内容'
}
},
}
</script>
2.子到父传值:$emit
首先在子组件中定义一个触发传值的事件,绑定到$emit,并将需要传给父组件的值一起传入。
<template>
<div class="son">
<p>{{ sonMsg }}</p>
<p>子组件接收到内容:{{ psMsg }}</p>
<!---- 绑定事件 --->
<button @click="setUser">传值</button>
</div>
</template>
<script>
export default {
name: "son",
props:['psMsg'],//接收psMsg值
data(){
return {
sonMsg:'子组件',
user:'子传父的内容'
}
},
methods:{
//绑定到$emit
setUser:function(){
this.$emit('chuanzhi',this.user)
}
}
}
</script>
然后父组件准备接收,这边接收的事件要与子组件绑定的事件名相同,
<template>
<div class="parent">
<h2>{{ msg }}</h2>
<p>父组件接手到的内容:{{ username }}</p>
<son @chuanzhi="getuser"></son> <!-- 绑定子组件事件 -->
</div>
</template>
<script>
import son from './Son' //引入子组件
export default {
name: 'HelloWorld',
data () {
return {
msg: '父组件',
zhi:'传的值',
username:''
}
},
components:{son},
methods:{
getuser(use){
this.username = use;
}
}
}
</script>
以上就是vue父子组件之间传值的基本用法,个人见解,不喜勿喷,欢迎交流。
当然关于传值这边还可以用vueX.具体资料及用法下次再记录。