<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TodoList</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model="inputValue">
<button @click='addItem'>提交</button>
<!-- <ul>
<li v-for="item in list">{{item}}</li>
</ul>-->
<ul>
<todo-item
v-for="(item, index) in list"
:index='index'
:content="item"
@delete="handleItemDelete"></todo-item>
</ul>
</div>
<script>
//Vue.component("TodoItem", {
// props: ['content'],
// template: "<li>{{content}}</li>"
//})
// 子组件定义
var TodoItem = {
// 接收参数
props: ['content', 'index'],
template: "<li @click='itemClick'>{{content}}</li>",
methods: {
itemClick() {
// 把index作为参数,带给父组件
this.$emit("delete", this.index)
}
}
}
var app = new Vue({
el: '#app',
components: {
TodoItem
},
data: {
list: [],
inputValue: ''
},
methods: {
addItem() {
this.list.push(this.inputValue)
this.inputValue = ''
},
handleItemDelete(index) {
console.log("handleItemDelete", index)
// 从list数组中删除index坐标开始1个元素。
this.list.splice(index, 1)
}
}
})
</script>
</body>
</html>