vue中父組件向子組件傳值使用props,非父子組件間傳值時可以使用事件總線,或者使用vuex,來看下事件總線的例子。
上代碼,如下:
1、vue-bus.js
List-1 vue-bus.js
const install = function (Vue) {
const Bus = new Vue({
methods: {
emit(event, ...args) {
this.$emit(event, ...args);
},
on(event, callback) {
this.$on(event, callback);
},
off(event, callback) {
this.$off(event, callback);
}
}
});
Vue.prototype.$bus=Bus;//由於放在原型上
};
export default install;
之後在main.js中引入vue-bus.js,如下List-2所示。
List-2
import VueBus from './vue-bus'
Vue.use(VueBus);
之後創建一個counter.vue,可以放在vue腳手架的components下,也可以放在其它目錄,如下
2、counter.vue
List-3 counter.vue
<template>
<div>
{{number}}
<button @click="handleAddRandom">隨機增加</button>
</div>
</template>
<script>
export default {
name: "counter",
props: {
number: {
type: Number
}
},
methods: {
handleAddRandom() {
const num = Math.floor(Math.random() * 100 + 1);
console.log("生產的num:" + num);
this.$bus.emit('add', num);
}
}
}
</script>
<style scoped>
</style>
對上面List-3的說明,會接收來自父組件的參數number,並顯示出來;有個按鈕,點擊會調用函數handleAddRandom,生成一個隨機數,並調用事件總線的emit方法,將隨機數給事件總線,由事件總線。
3、index.vue
創建index.vue
List-4 index.vue
<template>
<div>
隨機增加:
<counter :number="number"></counter>
</div>
</template>
<script>
import counter from './counter'
export default {
name: "index",
components: {
counter
},
data() {
return {
number: 0
}
},
methods: {
handleAddRandom(num) {
this.number += num;
}
},
created() {
//this.$bus.on需要在created中使用,否則不會生效
this.$bus.on('add', this.handleAddRandom);
},
beforeDestroy() {
//需要在beforeDestroy中移除
this.$bus.off('add', this.handleAddRandom);
}
}
</script>
<style scoped>
</style>
List-4中,引入counter.vue,作爲其子組件,定義數據number,並傳給子組件;在created方法中通過$bus.on來監聽"add",之後會調用handleAddRandom方法。
List-5 在router中使用之前創建vue組件
import Vue from 'vue'
import Router from 'vue-router'
import indexBus from 'components/vuebus/index'
Vue.use(Router);
export default new Router({
routes: [
....
{
path: '/indexBus',
name: 'indexBus', //路由名稱,
component: indexBus //對應的組件模板
},
]
})
整體如下圖1所示。
圖4.1
Reference:
1、樑灝,Vue.js實戰,清華大學出版社