父子组件通信
-
父组件中定义一个数据
-
在父组件的模板中,用 v-bind 将父组件的数据绑定在子组件身上
<Son :aa = "money"></Son>
-
在子组件的选项中,通过props选项来接收这个属性
-
这个属性可以在子组件的模板中以全局变量的形式使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<Father/>
</div>
<!-- father 组件 --start -->
<template id="father">
<div>
<h3> 这里是父组件 </h3>
<hr>
<Son :aa = "money"></Son>
</div>
</template>
<!-- father 组件 --end -->
<!-- son组件 --start -->
<template id="son">
<div>
<h4> 这里是子组件 </h4>
<p> 老爸给了我 {{ aa }} 生活费 </p>
</div>
</template>
<!-- son组件 --end -->
</body>
<script src="../../lib/vue.js"></script>
<script>
Vue.component('Father',{
template: '#father',
data () {
return {
money: 3000
}
}
})
Vue.component('Son',{
template: '#son',
props: ['aa']
// props: {
// 'aa': Number //属性验证
// }
// props: {
// 'aa': {
// validator ( val ) {
// return val > 2000
// }
// }
// }
})
new Vue({
el: '#app'
})
</script>
</html>
子父组件通信
- 子父通信流程
1. 现在子组件中定义一个数据
Vue.component('Son',{
template: '#son',
data () {
return {
money: 1000
}
}
})
2. 在父组件中也定义一个数据,这个数据用来接收子组件传递过来的数据
Vue.component('Father',{
template: '#father',
data () {
return {
bank: 1000
}
},
})
-
在父组件中定义一个事件处理程序,用于改变父组件定义的数据,这个事件处理程序是有参数的,这个参数就是子组件传递过来的数
Vue.component('Father',{ template: '#father', data () { return { bank: 1000 } }, methods: { bankAdd ( val ) { //val就是子组件给的数据 this.bank += val } } })
-
事件处理程序通过事件绑定的形式绑定在子组件身上
<Son @aa = "bankAdd"
- 定义一个事件处理程序,这事件处理程序中通过 this.$emit来触发自定义事件,并传递一个参数给父组件
Vue.component('Son',{
template: '#son',
data () {
return {
money: 1000
}
},
methods: {
give () {
// this.$emit('aa',传递给父组件的参数)
this.$emit('aa',this.money)
}
}
})
<template id="son">
<div>
<h4> 这里是子组件 </h4>
<button @click = " give "> 给老爸红包 </button>
</div>
</template>