vue父子组件
使用子组件类似于jsp动态引入页面,我们可以将一些可复用的功能或者页面封装成一个子组件,在需要用到时,在父组件中进行注册后,才能使用;
父子组件之间的通信是通过
e
m
i
t
和
emit和
emit和on以及props来进行数据的传递
<!DOCTYPE html>
<html>
<head>
<title>父子组件数据传递</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<style type="text/css">
.parent{
background:#0ff;
}
</style>
</head>
<body>
<div id="app">
<p>子组件随父组件改变</p>
<input v-model="parentMsg" class="parent">
<child :child_msg="parentMsg" ></child>
<p>自定义事件</p>
<p >{{total}}</p>
<diy_child @parent="parentClick"></diy_child>
<diy_child @parent="parentClick"></diy_child>
</div>
<script >
//注册组件 子组件标签名不能出现大写字母 会出现无法识别标签问题
Vue.component("child",{
props:["child_msg"],
template: "<p>子组件得到的数据---->{{child_msg}}</p>"
})
Vue.component("diy_child",{
template:"<button @click='childClick'>{{count}}</button>",
data:function(){
return {count : 0}
},
methods:{
childClick:function(){
this.count++
/*
*$emit用来触发父组件的方法,也可以添加可选参数向父组件传递数据
*父组件通过$on来监听$emit所传递的数据,二者的事件名必须保持一致
*/
this.$emit('parent')
}
}
})
new Vue({
el:"#app",
data:{
total:0,
parentMsg : "这是父组件的数据"
},
methods:{
parentClick:function(){
this.total++
}
}
})
</script>
</body>
</html>