<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue</title>
<script src="./js/vue.js"></script> //引入js
</head>
<body>
<div id="app">
<input v-model="inputValue"/>
<button @click="handleSubmit">submit</button>
<ul>
<todo-item
v-for="(item,index) of list" //循环取出list内的元素
:key="index" //vue的循环列表需要添加 :key="唯一标识" ,否则会有warning
:content="item"
:index="index"
@delete="handleDelete"
>
</todo-item>
</ul>
</div>
</body>
//父组件可以使用 props 把数据传给子组件。
//子组件可以使用 $emit 触发父组件的自定义事件。
//body循环时加入下标index,以及订阅发布事件@delete
//当字组件内触发$emit的自定义事件,同时调用handleDelete方法,传参即为index
<script>
//全局组件
// Vue.component('todo-item',{
// template:'<li>item</li>'
// })
//局部组件
var todoItem = {
props:['content','index'], //props属性用来接收父组件传给子组件的数据
template:'<li @click="handleClick">{{content}}</li>',
methods: {
handleClick(){
this.$emit('delete',this.index) //点击handleClick方法,触发自定义事件delete
}
}
}
//this.$emit(event,arg) 触发当前实例上的事件
new Vue({
el:"#app",
components:{
'todo-item':todoItem //定义组件
},
data:{
list:[],
inputValue:''
},
methods:{
handleSubmit(){
this.list.push(this.inputValue);
this.inputValue=''
},
handleDelete(index){
this.list.splice(index,1) //删除时下标及位数
}
}
})
</script>
</html>
//本页学习慕课网Dell老师课程的笔记,感谢大佬的技术分享