<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="box">
<my-father></my-father>
</div>
<script src="js/vue.js"></script>
<script>
Vue.component("my-father",{
template:`
<div>
<p>內(nèi)容:{{message}}</p>
<my-child @sentMsg="sent"></my-child>//第一個(gè)子組件第二個(gè)父組件為了調(diào)用
</div>
`,
data:function(){
return{
message:''//為了父組件方便接收
}
},
methods:{
sent:function(text){//text是形參 子組件內(nèi)函數(shù)是實(shí)參
this.message=text
}
}
})
Vue.component("my-child",{
template:`
<div>
<input type="text" v-model="messages"/>
<button @click="add">添加</button>//加button是為了觸發(fā)事件
</div>
`,
data:function(){
return{
messages:""http://數(shù)據(jù)必須寫在子組件中
}
},
methods:{
add:function(){
this.$emit("sentMsg",this.messages)
this.messages=""
}
}
})
new Vue({
el:".box"
})
</script>
</body>
</html>
QQ圖片20180921191212.png