直接上代码
vm.$emit( eventName, […args] )
触发当前实例上的事件 可选附加参数 传给监听器回调。
<style>
#app{ margin: 100px; }
#app>input, #app>button, ul li button{ border: none; outline: none; box-shadow: 0 1px 6px #dedede; background: #fff; }
#app>input:focus, #app>button:hover, ul li button:hover{ box-shadow: 0 2px 4px #ccc; }
#app>input{ padding: 6px 10px; 200px; }
#app>button{ padding: 6px 10px; height: 30px; cursor: pointer; }
ul{ padding: 0; }
ul li{ 280px; list-style: none; margin-top: 10px; }
ul li button{ float: right; 30px; cursor: pointer; }
</style>
<div id="app">
<input v-model="txt" type="text" @keyup.enter="handleSubmit">
<button @click="handleSubmit">submit</button>
<ul>
<todo-item
v-for="(item, index) in list"
:key="index"
:content="item"
:index="index"
@delete="handleDelete"
></todo-item>
</ul>
</div>
<script>
Vue.component('todo-item', {
props: ['content', 'index'],
template: '<li>{{index}}. {{content}} <button @click="handleClick">x</button></li>',
methods: {
handleClick () {
this.$emit('delete', this.index)
}
}
})
new Vue({
el: '#app',
data: {
txt: '',
list: []
},
methods: {
handleSubmit () {
if(!this.txt) return;
this.list.push(this.txt);
this.txt = '';
},
handleDelete (index) {
this.list.splice(index, 1)
}
}
})
</script>