Vue组件通信整理:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| <div id="app"> <h2># parent & child</h2> <ol> <li>props[$attrs & $listeners] $emit[.sync]</li> <li>$parent $children/ref</li> <li>eventBus</li> <li>Vuex $root</li> <li>slot</li> <li>provide inject</li> </ol> <parent-child :name.sync="name" ref="parentChild" @say="receive"></parent-child> <button @click="childFn">What's your name, parent-child?</button> Change Name: <input type="text" v-model="name"> <hr> <h2># child & child</h2> <ol> <li>子->父->子</li> <li>eventBus</li> <li>Vuex $root</li> </ol> <child-brother></child-brother> <child-sister></child-sister> </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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| Vue.component('parent-child', { props: ['name'], methods: { alertName() { alert('I am ' + this.name) }, say() { this.$emit('say', 'I am fine') }, parentFn() { this.$parent.receive() } }, template: ` <div> <p>Name: {{name}}</p> <button @click="say">Say something</button> <button @click="parentFn">Hello Parent?</button> <button @click="$emit('update:name', 'Awesome Jack')">Change name self</button> </div> ` })
Vue.component('child-brother', { methods: { sayHello() { eventBus.$emit('talking', 'Hello') } }, template: ` <div> <p>brother</p> <button @click="sayHello">hello my sister</button> </div> ` })
Vue.component('child-sister', { mounted() { eventBus.$on('talking', (words) => { alert('Received from brother: ' + words) }) }, template: ` <div> <p>sister waiting brother takling...</p> </div> ` })
let eventBus = new Vue() new Vue({ el: '#app', data() { return { name: 'Jack' } }, methods: { childFn() { this.$refs.parentChild.alertName() }, receive(msg) { if (msg) { alert(`${this.name} said: ${msg}`) } else { alert('Received: Nothing') } } } })
|
运行Demo见:https://codepen.io/itibbers/pen/yLBJddd