跨组件【订阅/发布】模式
描述:vue2.0支持
1 2 3 4 5 6 7 8
| var bus = new Vue();
bus.$emit('fcName',1)
bus.$on('fcName',function(id){ console.log(id); });
|
通过prop向子组件通信
1 2 3 4 5
| <div id="app"> <p>{{ total }}</p> <button type="button" @click="clickRef">调用子组件</button> <child :message="total"></child> </div>
|
message前加”:” total是动态数据,未加total是静态数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| Vue.component('child',{ template:'<div>全局组件:{{ message }}</div>', props: { message: [String, Number] } }); var vm = new Vue({ el: '#app', data: { total: 1 }, methods: { clickRef: function(){ this.total++; } } });
|
子组件调用父组件
1 2 3 4
| <div id="app"> <p>{{ total }}</p> <simple @increment = "parentFn"></simple> </div>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| Vue.component('simple',{ template: '<button @click="fns">子组件click</button>', methods: { fns: function(){ this.$emit('increment'); } } });
var vm = new Vue({ el: '#app', data: { total: 1 }, methods: { parentFn: function(){ this.total++; } } });
|
备注:该方式主要通过子组件emit()方法来实现。
父组件调子组件方法和数据
1 2 3 4 5
| <div id="app"> <p>总次数:{{ total }}</p> <button @click="parentClick">调子组件</button> <simple ref="children"></simple> </div>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| Vue.component('simple',{ template: '<button @click="fns">子组件次数({{ num }})</button>', data: function(){ return { num: 0} }, methods: { fns: function(){ this.num++; } } }); var vm = new Vue({ el: '#app', data: { total: 1 }, methods: { parentClick: function(){ this.total++; var child = this.$refs.children; child.fns(); } } });
|
使用v-model进行通信
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| Vue.component('my-component', { template: `<div>{{currentVal}}这是:,<button @click="foo">传递</button></div>`, props: ['value'], data() { return { currentVal: this.value } }, watch: { currentVal(val) { this.$emit('input', val) }, value(val){ this.currentVal = val } }, methods: { foo() { this.currentVal++ }, }, })
var appMain = new Vue({ el: '#app', data: { num: 3, }, methods: { clickMe() { this.num ++ } } })
|
html
1 2 3 4 5
| <div id="app"> <p>总次数:{{ total }}</p> <button @click="parentClick">调子组件</button> <simple ref="children"></simple> </div>
|
转载: Y. Jer 的虚拟笔记