先看个一般的例子:
// 我们需要将信息从子组件传递给父组件,(有可能不止一条信息,因此)肯定需要一个标识,这个标识放在$emit里面(js),在dom中通过@来关联父元素。如下:
<div id = "app">
<transfer @connect="sayConnect" @build="sayBuild"></transfer>
</div>
// js
<script>
Vue.component('transfer',{
template:
'<button @click="send1">发送connect</button><br>'+
'<button @click="send2">发送build</button>',
methods:{
send1(){
this.$emit('connect');
},
send2(){
this.$emit('build');
}
}
});
// 子组件注册了2个方法,send1和send2,点击send1发送connect,点击send2发送build.
// @connect="sayConnect", connect对应子组件中this.$emit('connect').sayConnect对应父组件的sayConnect方法,下面写出来.
// 注意,在子模版中,按钮的绑定使用的是@而不是:
let vm = new Vue({
el:"#app",
methods:{
sayConnect(){
console.log('connect success!');
},
sayBuild(){
console.log('build success');
}
}
});
</script>
接下来,看个更复杂一点的例子:
假设我们希望:
点击"+1",总数加1;点击"-1"总数减1. 且数据是来自子组件…
首先写html
<div id = "app">
<p>总数 {{ total }} </p>
<my-component @increase="handleTotal" @reduce="handleTotal"> </div>
</div>
// 说明: total 是父元素的
// @increase 对应 子组件中的 $emit('increase', data);
// @reduce 对应 子组件中的 @emit('reduce', data);
// handleTotal对应父组件中methods方法中的 handleTotal方法
挂载Vue,注册组件
<script>
// 组件应该在vue挂载之前注册
Vue.component('my-component',{ // 第一个参数组件名,对应html中的<my-component></my-component>
// 首先写替换<my-component>的template
template:'\
<div>\
<button @click = "handleIncrease"> +1 </button>\
<button @click = "handleReduce">-1 </button>\
<div>',
// ps: template中 写了2个点击事件 handleIncrease 和 handleReduce , 由于要传一个数据给父元素,我们定义如下:
data: function (){
return {
counter: 0;
}
}, // 子元素中的counter 初始化为0
methods: {
handleIncrease: function() {
this.counter++;
this.$emit('increase', this.counter);
},
handlerReduce: function() {
this.counter--;
this.$emit('reduce', this.counter);
}
}
});
// 子模块完毕
// 说明: $emit(a,data)用来像父元素传递信息, 父元素用@'a'的形式接受信息
// 开始挂载vue(在此是父元素).
var app = new Vue({
el: '#app',
data: {
total: 0 // 对应html <p>{{total}} </p>
},
methods:{
handleTotal: function (total ){ // total 参数来自于 $emit的第二个参数..
this.total = total;
}
}
})
</script>