console
//顺序,先写组件,再写实例
//组件1
Vue.component('welcome-button', {
template: `
<button v-on:click="$emit('welcome')">
Click me to be welcomed
</button>
`
})
//实例1
var vm1 = new Vue({
el: '#emit-example-simple',
methods: {
sayHi: function () {
console.log('Hi!')
}
}
})
//组件2
Vue.component('magic-eight-ball',{
// data: {}
data: function () {
return {
possibleAdvice: ['yes','no','maybe']
}
},
methods: {
giveAdvice: function () {
// 0 1 2
var randomAdviceIndex = Math.floor(Math.random()*this.possibleAdvice.length)
// 触发当前实例(子组件/当前组件))上的事件。附加参数(第二个参数)都会传给监听器(父组件)回调。
this.$emit('give-advice',this.possibleAdvice[randomAdviceIndex])
}
},
template: `
<button @click="giveAdvice">
Click me for advice
</button>
`
})
//实例2
var vm2 = new Vue({
el:"#emit-example-argument",
methods: {
//接收子组件传递的参数,
showAdvice: function (advice) {
console.log(advice)
}
}
})
<!-- 只配合一个事件名使用 $emit: -->
<div id="emit-example-simple">
<welcome-button v-on:welcome="sayHi"></welcome-button>
</div>
<!-- 配合额外的参数使用 $emit: -->
<div id="emit-example-argument">
<!-- 常用,父组件将showAdvice事件以give-advice名称传递到子组件magic-eight-ball
子组件magic-eight-ball接收give-advice,之后定义data数据,
模板template(是一个button,点击执行giveAdvice事件)
事件是giveAdvice,定义random随机数0 1 2 ,然后通过$emit实现触发give-adcice,
将第二个参数传递(this.possiveAdvice[randomAdviceIndex])给父组件,
最后参数传递到showAdvice,实现父子组件数据联动
$emit的作用是触发当前实例上的事件。附加参数都会传给监听器回调。-->
<magic-eight-ball v-on:give-advice="showAdvice"></magic-eight-ball>
</div>