VUE父子组件通信
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<parent></parent>
</div>
</body>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
//子组件
let chiled = {
template:`
<div>
<p>我是子组件:{{name}}</p>
<button @click="changeName()">changeName</button>
</div>
`,
props:{
name:{
type:String,
required:true,
default:'hello'
}
},
methods: {
changeName(){
//子传父
this.$emit("getName","lily")
}
}
};
// 父组件
let parent = {
template:`
<div>
<p>我是父组件:</p>
//接收子传父的参数
<chiled :name="name" @getName="setName"></chiled>
</div>
`,
components: {
chiled
},
data(){
return {
name:"boat",
}
},
methods: {
setName(val){
this.name = val;
}
}
};
new Vue({
el:"#app",
components:{
parent
},
data:{
n: 0
},
methods:{
addnum(){
this.n++;
}
}
});
</script>
</html>