这里我没用脚手架,可以用html和js的思维了解,最重要的是这次的音乐是我最喜欢的Flower Dance
据说父子组件通信很难理解,瑟瑟发抖的写一下
先说它们的通信方式不是移动联通电信~
父组件把数据传给子组件用props
用法:1
2
3
4
5
6
7//subassembly是一个注册了的子组件
<subassembly v-for="(item,index) in list" :content="item"></subassembly>
Vue.component('subassembly', {
props: ['content'],
template: '<li>{{content}}</li>'
});
item是父组件v-for循环出来的东西
这个会做成单独的组件是为了应付数据多的时候单独做成一个组件比较好
子组件可以使用 $emit 触发父组件的自定义事件,也可以用on事件监听
1 | vm.$emit( event, arg ) //触发当前实例上的事件处理函数 |
这里用$emit举例假如要删掉生成的数据,这时候需要在子组件写这样的方法1
2
3
4
5
6
7
8
9Vue.component('subassembly', {
props: ['content', 'index'],
template: '<li @click="handleFunction">{{content}}</li>',
methods: {
handleFunction: function () {
this.$emit('delete', this.index)
}
}
});
这样子组件被点击的时候就会触发delete,此时父组件v-on了一个delete触发父组件的delfunction方法,并且传过去一个index1
2
3
4
5
6
7
8
9
10
11
12
13
14
15<subassembly
v-for="(item,index) in list" :key="index" :content="item"
:index="index"
@delete="delfunction">
</subassembly>
Vue.component('subassembly', {
props: ['content', 'index'],
template: '<li @click="handleFunction">{{content}}</li>',
methods: {
handleFunction: function () {
this.$emit('delete', this.index)
}
}
});
delfunction:1
2
3
4delfunction: function (index) {
alert("删掉了");
this.list.splice(index, 1);
}
父组件接收到子组件传过来的index之后就删掉相应数据,vue是数据驱动的,这么干就实现了删除功能
有点绕。
非父子组件通信
非父子组件通信可以用vuex和下面举例的这个方法,当然一般用vuex比较好。
官网的api指出可以使用空vue实例作为事件中央线!也就是说非父子组件之间的通信,必须要有公共的实例(可以是空的),才能使用 $emit 获取 $on 的数据参数,实现组件通信。
比如现在创建了cail组件,希望让他们的值可以互传1
2<cail content="brother1"></cail>
<cail content="brother2"></cail>
先定义一个公共的中央线1
Vue.prototype.bus = new Vue();
给组件绑定上一个sonclick事件,然后通过$emit传参1
2
3sonhandl: function () {
this.bus.$emit('sonclick', this.soncontent);
}
因为vue是单向数据流关系,不允许子修改父组件的数据,虽然不会报错,但是会报警告,所以在声明子组件的时候只能定义一个soncontent来装父级传过来的content。1
2
3
4data: function () {
return {
soncontent: this.content
}
接着用钩子函数通过$on监听sonclick事件1
2
3
4
5
6mounted: function () {
var this_ = this;
this.bus.$on('sonclick', function (msg) {
this_.soncontent = msg;
})
}
这样就实现了点击brother1的时候,组件值也传到brother2
理解简单点就是兄组件绑定一个handelFunction1
2
3
4
5
6<div @click="handelFunction"></div>
methods: {
handelFunction() {
vm.$emit('hanFunction','HHardyy'); //触发事件
}
}
弟组件on监听hanFunction1
2
3
4
5created() {
vm.$on('hanFunction', (re) => {
this.test= re; // 接收HHardyy
});
}
可以理解成1
2
3
4
5
6
7
8var bus = new Vue()//这个可以新建一个event.js,里头let bus=new Vue(); 然后把把bus向外export
// 触发组件 A 中的事件
bus.$emit('id-selected', 1)
// 在组件 B 创建的钩子中监听事件
bus.$on('id-selected', function (id) {
// ...
})