新建child.vue,在App.vue中添加:
<child fatherCall="where are you , my son"></child>
import child from './components/child'
components: {
child
}
这样App.vue是child.vue的父组件,可以看到,在child标签中:fatherCall=”where are you , my son”,fatherCall是我们希望传递到child的,它的值为“where are you , my son”。
在child.vue中如何去接受fatherCall呢?vue中使用了props,在child.vue中添加代码:
props:["fatherCall"]
这样,fatherCall可以在child.vue中随时使用,通过this.fatherCall访问。
如果传递的值是一个对象,如:
fatherMgs:[
{
index: 1,
mgs: "this the first mgs"
},
{
index: 2,
mgs: "this the second mgs"
},
{
index: 1,
mgs: "this the third mgs"
},
]
这时需要用到v-bind:
<child v-bind:fatherMgs="fatherMgs"></child>
同样child.vue中通过props接受数据:
props:["fatherMgs"]
循环读取fatherMgs
<li v-for="item in fatherMgs">{{item.index}}.{{item.mgs}}</li>
2.子组件向父组件传值
主要使用vue中的emit,官方解释:触发当前实例上的事件。附加参数都会传给监听器回调。反正看不懂什么意思,直接拿来用。
首先在child.vue中添加代码:
<button v-on:click="sendMgsToFather">发消息给父亲</button>
当点击按钮时,调用函数sendMgsToFather:
sendMgsToFather:function () {
this.$emit("listenToChild","I'm watching TV")
}
这时可以理解为child.vue,告诉App.vue,我触发了listenToChild事件,参数值为“I’m watching TV”。
这时App.vue中的child.vue组件为:
<child v-on:listenToChild="listenToChildFun"></child>
表示当出发时间listenToChild时,会调用函数listenToChildFun,参数就是之前传过来的I’m watching TV”。
listenToChildFun:function (childCall) {
//处理...
}