Vue——自定义事件
由于Vue中的其他组件无法使用到Vue实例中的数据,可以通过自定义事件完成对Vue实例中数据的一些操作,具体图解如下:
其中,由于Vue中具有的数据双向绑定的特性,使得前端可以作为组件与实例的桥梁,利用自定义事件实现一些功能。
示例代码:
//前端
<div id="app" >
<todo>
<todo-title slot="todo-title" :title="title"></todo-title>
<todo-items slot="todo-items" v-for="(item,index) in items" :item="item"
:index="index" :key="index" v-on:remove="removeItems(index)"></todo-items>
</todo>
</div>
//Vue
<!--导入Vue-->
<script type="text/javascript" src="https://cdn.bootcss.com/vue/2.5.17-beta.0/vue.js"></script>
<script type="text/javascript">
//slot:插槽
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: '<div>{{title}}</div>'
});
Vue.component("todo-items",{
props: ['item','index'],
//记得button绑定事件
template:'<li>{{index}}---{{item}}<button @click="remove">删除</button></li>',
methods:{
remove:function(index){
this.$emit('remove',index);
}
}
});
var vm = new Vue({
el:'#app',
data: {
title: "书籍列表",
items:['Java','Math','English']
},
//methods不要放进data里!!
methods: {
removeItems:function (index){
console.log("删除了"+this.items[index]);
this.items.splice(index,1);
}
}
});
</script>
关于V-bind key="":
}
}
});
**关于V-bind key="":**
>一句话,**key的作用主要是为了高效的更新虚拟DOM**。另外vue中在使用相同标签名元素的过渡切换时,也会使用到key属性,其目的也是为了让vue可以区分它们。