<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TodoList</title>
// 通过<script>标签引入vue.js文件,vue.js文件可在Vue官网下载
<script src="./vue.js"></script>
</head>
<body>
<div id="root">
<div>
<input type="text" v-model="todoValue" />
<button @click="handleBtnClick">添加</button>
</div>
<ul>
<!-- <li v-for="item in list">{{item}}</li> -->
<!-- 使用自定义的组件 -->
<!-- v-bind简写冒号,即"v-bind"简写为":" -->
<!-- v-on:简写"@" -->
<todo-item :content="item"
:index="index"
v-for="(item, index) in list"
@delete="handleItemDelete">
</todo-item>
</ul>
</div>
<script>
// 全局组件
// Vue.component("TodoItem", {
// props: ['content'],
// template: "<li>{{content}}</li>"
// })
// 局部组件
var TodoItem = {
props: ['content', 'index'], // 接收外部传递过来的数据
template: "<li @click='handleItemClick'>{{content}}</li>" , // 子组件的模板
methods: {
handleItemClick: function() {
this.$emit("delete", this.index);
}
}
};
// 创建Vue实例
var app = new Vue({
el: '#root',
// 注册局部组件到Vue实例
components: {
TodoItem: TodoItem
},
data: {
todoValue: '',
list: []
},
methods: {
handleBtnClick: function() {
this.list.push(this.todoValue);
this.todoValue = '';
},
handleItemDelete: function(index) {
this.list.splice(index, 1);
}
}
})
</script>
</body>
</html>