一切從簡(jiǎn),不用webpack。
1. props $emit
主要是父子之間通信,兄弟之間通信。
<!-- html -->
<!DOCTYPE html>
<html>
<head>
<script src="http://vuejs.org/js/vue.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="app">
<p>父組件中的值parentNum: {{ parentNum }}</p>
<add-component :transfer=parentNum @change=plus></add-component>
<reset-component @reset=reset></reset-component>
<button @click=fatherAdd>父組件自增</button>
</div>
</body>
</html>
Vue.component('add-component', {
template: `
<div>
<div>子組件中的值childNum: {{childNum}}</div>
<button @click="increment">子組件中自增</button>
</div>
`,
props: {
transfer: {
Number,
}
},
watch: {
'transfer': function(childNum) {
this.childNum = childNum;
}
},
data() {
console.warn('transfer:' + this.transfer);
return {
childNum: this.transfer
}
},
methods: {
increment() {
this.childNum++;
this.$emit('change', this.childNum)
}
},
});
Vue.component('reset-component', {
template: `
<div>
<button @click=reset>重置</button>
</div>
`,
methods: {
reset() {
this.$emit('reset');
}
}
});
new Vue({
el: '#app',
data: {
parentNum: 0
},
methods: {
fatherAdd() {
this.parentNum += 1;
},
plus(newNum) {
console.log('newNum:' + newNum);
this.parentNum = newNum;
},
reset() {
this.parentNum = 0;
}
}
})
父子之間通信說(shuō)明:
父組件向子組件add-component傳遞初始值parentNum,子組件通過(guò)props接受并自定內(nèi)部變量用childNum,子組件中有一個(gè)按鈕,每點(diǎn)擊一下數(shù)值就會(huì)自增1。
如果子組件用了自己的變量而不是直接用的父組件的變量,則需要通過(guò)watch來(lái)實(shí)時(shí)更新子組件的內(nèi)容 。
watch transfer表示: 一旦父組件更新了,立馬傳遞到子組件中。
子組件通過(guò)$emit方法向父組件傳遞數(shù)值。
兄弟組件通信說(shuō)明:
reset-component是add-component的兄弟組件,本示例中無(wú)法直接通信,可借助父組件通信。
2. eventBus
/新建一個(gè)Vue實(shí)例作為中央事件總嫌/
let event = new Vue();
/監(jiān)聽事件/
event.$on('eventName', (val) => {
//......do something
});
/觸發(fā)事件/
event.$emit('eventName', 'this is a message.');