<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>子组件和父组件通信(发布订阅模式)</title>
<script src="./vue.js"></script>
</head>
<body>
<!-- 每个组件实际就是一个实例 -->
<!--子向父传值 子组件通过$emit发布事件,父组件订阅了该事件就会触发 -->
<!--父向子传值,通过props传值 -->
<div id="root">
<div>
<input v-model="inputValue"/>
<input type="button" value="提交" @click="handleClick">
</div>
<ul>
<todo-item v-for="(item,index) in list" :key="index" :content="item" :index="index" @delete1="handleDelete"></todo-item>
</ul>
</div>
<script>
Vue.component('todo-item',{
props:['content','index'],
template:'<li @click="handleClick">{{content}}</li>',
methods:{
handleClick:function(){
this.$emit('delete1',this.index); //触发事件
}
}
})
new Vue({
el:"#root",
data:{
inputValue:'',
list:[]
},
methods:{
handleClick:function(){
this.list.push(this.inputValue);
this.inputValue="";
},
handleDelete:function(index){
this.list.splice(index,1);
}
}
})
</script>
</body>
</html>
注:学习笔记内容来自:https://www.imooc.com/learn/980
官网:cn.vuejs.org