什么叫做自定义事件内容分发呢?
简单来说就是,如果在vue中,我们需要自定义的东西要交给前端的话,不能直接交给前端,而是需要一个中间环节,这个时候就需要内容分发。
参考我们上一个案例,我们把列表数据都展示出来了,现在我们想添加一个删除事件,点击删除按钮就可以删除数据。
由于我们采用的是自定义的模板组件,因此第一步的思路就是在模板中定义一个按钮,并且他有一个删除事件的方法。
<todo>
<todo-title slot="todo-title" :title="title"></todo-title>
<todo-items slot="todo-items" v-for="(item,index) in todoItems"
v-bind:item="item" ></todo-items>
</todo>
Vue.component("todo",{
template: '<div> \
<slot name="todo-title"></slot>\
<ul>\
<slot name="todo-items"></slot>\
</ul>\
</div>'
});
Vue.component("todo-title",{
props: ['title'],
template: '{{title}}'
});
Vue.component("todo-items",{
props: ['item','index'],
//只能绑定当前组件的方法
template: '{{index}}-------{{item}} ',
methods: {
remove: function (index){
}
}
});
这就是我们的基本思路,在模板组件中添加一个删除按钮,然后在下面写我们的删除方法,通过下标来进行删除。
但是问题来了,数据不在组件中,而是在我们的vue实例中,我们不可能直接通过组件拿到vue实例中的数据,所以只能通过前端来拿,由于vue是MVVM的框架,是数据双向绑定的。
因此我们就引出了我们vue的自定义事件内容分发
我们首先在vue实例中写一个方法,让这个方法跟我们组件的方法在视图层进行绑定。
var vm = new Vue({
el:"#vue",
data: {
title: "列表",
todoItems: ['菜菜','你好','前端']
},
methods: {
removeItems:function (index){
console.log("删除了"+this.todoItems[index]+"OK");
this.todoItems.splice(index,1);//一次删除一个元素
}
}
});
我们这里写了一个removeItems的方法,通过前端传递下标属性,来进行删除数据。
Vue.component("todo-items",{
props: ['item','index'],
//只能绑定当前组件的方法
template: '{{index}}-------{{item}} ',
methods: {
remove: function (index){
//this.$emit('方法名',参数); 自定义事件分发
this.$emit('remove',index);
}
}
在组件中也定义一个下标的属性,以及删除的方法,并把这个方法通过 this.$emit
绑定起来。属性则通过props
来接收前端的数据。
拓展: this.$emit('自定义事件',属性)
将组件和vue实例通过前端进行绑定
<div id="vue">
<todo>
<todo-title slot="todo-title" :title="title"></todo-title>
<todo-items slot="todo-items" v-for="(item,index) in todoItems"
v-bind:item="item" v-bind:index="index" v-on:remove="removeItems(index)"></todo-items>
</todo>
</div>
我们这里通过v-for
循环也把下标循环出来了,并通过v-bind:index把他跟index属性绑定起来,通过v-on
把组件的方法和vue实例的方法绑定起来
注意: v-on和v-bind:组件的属性或名字=“vue实例的属性或方法”
这样就完成了我们自定义事件内容的分发。
我们再用图来整理我们的思路
1、前端和vue实例是数据双向绑定的,要记住这个思想
2、组件或者vue实例都只能获取自身的数据或者从前端传递的数据,组件不能直接从vue实例中获取
3、方法名一定要小写!
至此,我们vue的入门已经学完了,这并不是真正的vue,VUE的开发都是基于NodeJS,实际开发采用vue-cli
脚手架开发,vue-router
路由、vuex
做状态管理(Session),VUE UI一般使用ElementUI或者ICE来快速搭建前端项目