Vuejs第十篇之vuejs父子组件通信

2020-06-16 06:34:33易采站长站整理

【2】触发的绑定写在模板之中(即被替换的那个template模板中),可以多个子组件的事件绑定一个父组件的方法,或者不同子组件的事情绑定不同父组件的方法,但是不能同一个子组件事件绑定多个父组件的方法。

【3】子组件派发消息传递的参数,即使子组件的事件没有参数,也不影响将参数传递给父组件的方法(即父组件的方法可以接受到子组件方法获取的参数)

如示例:


<div id="app">
父组件:
<button>点击向下传播broadcast</button>
<br/>
子组件1:
<!--绑定写在这里,可以多个绑定同一个,或者不同绑定不同的,但不能一个绑定多个-->
<children v-on:test="parent" @test2="another"></children>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
val: 1
},
methods: {
parent: function (arg) {
console.log(arg);
console.log("the first method with test event");
},
another: function () {
console.log("another method");
}
},
components: {
children: { //这个无返回值,不会继续派发
props: ['test'],
template: "<button @click='childClick'>children1</button></br><button @click='childClick2'>children1</button>",
methods: {
childClick: function () {
this.$emit("test", 'the argument for dispatch');
},
childClick2: function () {
this.$emit("test2");
}
},
events: {
test: function () {
console.log("test");
},
test2: function () {
console.log("test2");
}
}
}
}
});
</script>

④子组件索引

简单来说:就是可以直接从索引获取到子组件,然后就可以调用各个子组件的方法了。

添加索引方法是:在标签里添加v-ref:索引名

调用组件方法是:vm.$ref.索引名

也可以直接在父组件中使用this.$ref.索引名

这个时候,就可以获得组件了,然后通过组件可以调用他的方法,或者是使用其数据。

示例代码:


<div id="app">
父组件:
<button @click="todo">触发子组件的事件</button>
<br/>
子组件1:
<!--绑定写在这里,可以多个绑定同一个,或者不同绑定不同的,但不能一个绑定多个-->
<children v-ref:child></children>
</div>
<script>
var vm = new Vue({
el: '#app',
methods: {
todo: function () {
this.$refs.child.fromParent(); //通过索引调用子组件的fromParent方法
}
},
components: {
children: { //这个无返回值,不会继续派发
props: ['test'],
template: "<button>children1</button>",