父子组件通信
预备知识
props
props 可以是数组或对象,用于接收来自父组件的数据。props 可以是简单的数组,或者使用对象作为替代,对象允许配置高级选项,如类型检测、自定义校验和设置默认值。
emit
触发当前实例上的事件。附加参数都会传给监听器回调。
on
监听当前实例上的自定义事件。事件可以由vm.$emit触发。回调函数会接收所有传入事件触发函数的额外参数。
once
监听一个自定义事件,但是只触发一次,在第一次触发之后移除监听器。
off
移除自定义事件监听器。
如果没有提供参数,则移除所有的事件监听器;
如果只提供了事件,则移除该事件所有的监听器;
如果同时提供了事件与回调,则只移除这个回调的监听器。
例子
vue的数据流是单向的,父级 prop 的更新会向下流动到子组件中,但是反过来则不行。这样会防止从子组件意外改变父级组件的状态,从而导致你的应用的数据流向难以理解。
普通的props传参
Vue.component('blog-post', {
props: ['postTitle'],
template: '<h3>{{ postTitle }}</h3>'
})
<blog-post post-title="hello!"></blog-post>
我们在封装组件的时候会遇到这种情况,下面是使用了emit和props从子组件传参到父组件对比,发现使用emit更简便:
解释下这里把“hi”字符串看成参数,从子组件把“hi”传到父组件。
<template>
<div class="hello">
<button v-on:click="$emit('welcome','hi')">
Click me to be welcomed
</button>
</div>
</template>
<script>
export default {
}
</script>
<template>
<div class="home">
<HelloWorld v-on:welcome="sayHi" />
</div>
</template>
<script>
import HelloWorld from './HelloWorld.vue'
export default {
name: 'home',
components: {
HelloWorld,
},
methods: {
sayHi: function(hi) {
alert(hi)
}
}
}
</script>
使用props的方式:
<template>
<div class="home">
<HelloWorld :hi="sayHi" />
</div>
</template>
<script>
import HelloWorld from './HelloWorld.vue'
export default {
components: {
HelloWorld,
},
methods: {
sayHi: function(hi) {
alert(hi)
}
}
}
</script>
<template>
<div class="hello">
<button @click="sayhi">
Click me to be welcomed
</button>
</div>
</template>
<script>
export default {
props: {
hi: {type:Function}
},
methods:{
sayhi(){
this.hi("hello")
}
}
}
</script>
文中demo我放在了git上方便参考,git地址为: https://gitee.com/stones_song/vue-demo.git