<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="../vue.min.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="app">
<edit></edit>
<list></list>
</div>
<template id="edit">
<div>
<input type="text" v-model="str"/>
<button @click="add()">添加</button>
</div>
</template>
<template id="list">
<ul>
<li v-for="(item,index) in arr">{{item}}
<button @click="remove(index)">删除</button>
</li>
</ul>
</template>
</body>
<script type="text/javascript">
//定义一个中间vue实例,作为中间层传递数据
var vmcenter = new Vue({});
//编辑组件
var edit = {
template:"#edit",
data:function(){
return{
str:''
};
},
methods:{
add:function(){
//通过中间层发送数据 $emit("事件名",数据)
vmcenter.$emit("zengjia",this.str)
console.log(this.str);
}
}
};
//列表组件
var list = {
template:"#list",
//组件内部data写法
data:function(){
return{
arr:["斌斌","航航"]
}
},
//删除
methods:{
remove:function(i){
this.arr.splice(i,1);
}
},
created:function(){
//监听 收到
var _this =this;
//监听组件1发的事件
vmcenter.$on("zengjia",function(data){
_this.arr.push(data);
})
}
}
new Vue({
el:"#app",
components:{
edit,
list
}
})
</script>
</html>