vue虽然支持双向绑定,可是组件之间总归而言仍是单项的,因此咱们在这一片内容之中将会去简单的了解和总结,咱们最日常的vue组件之间通讯是经过什么样的方式来的。vue
父 --> 子:咱们经常使用的props属性就是用来对父子组件进行内容的传递的。
vuex
父 --> 孙:bash
父组件:
methods:{
sayHello: function(name){
console.log('this is ' + name + ' saying hello!')
}
},
provide() {
return {
sayHello: this.sayHello
}
},
mounted() {
this.sayHello = function(){
console.log("saying hello after changed");
}
}
子组件:
inject:['sayHello'],
methods: {
handleInput (event){
const value = event.target.value;
this.sayHello("children");
this.$emit('input', value);
}
}
复制代码
p.s:这里咱们须要注意一点,使用依赖注入传递的值并非响应式的,因此咱们在父组件之中修改了传递的值的时候,子组件获取的值其实是没有变化以前的。ide
以上三种方式或多或少都确立了传递的结构,使得父子组件之间存在必定的耦合,因此咱们使用这些方式的时候都须要进行必定的考量,依据本身的需求选择通讯的方法。函数
子 --> 父:vue官方推荐的方式是以事件的形式来进行内容的传递。即父组件之中绑定事件函数,留定传递数值的形参,子组件之中经过$emit来调用传递的方法而且传递改变的值信息。上示例:学习
parent.vue:
<template>
<div>
<AInput @input="inputEvent" :value="inputContent"/>
<p>{{ inputContent }}</p>
</div>
</template>
<script>
import AInput from '@/components/Input.vue'
export default {
name: "state",
data () {
return {
inputContent: "",
};
},
components: {
AInput
},
methods:{
inputEvent:function(content){
this.inputContent = content;
}
}
}
children.vue:
<template>
<input @input="handleInput" :value="value"/>
</template>
<script>
export default {
name: "inputContent",
props: {
value:String
},
methods: {
handleInput (event){
const value = event.target.value;
this.sayHello(this.name);
this.$emit('input', value);
}
}
}
复制代码
使用Bus来进行装填管理控制,什么是BUS呢,实际上bus就是一个空的vue对象内容。咱们先来建立一个BUs:ui
import Vue from 'vue'
const Bus = new vue();
Vue.prototype.$bus = Bus;
复制代码
以后咱们能够在每个vue对象之中经过this.$bus来获取到当前的这个bus空对象。并使用它来进行内容的通讯。举一个简单的例子。this
componentOne.vue:
data:() => ({
content: "check"
}),
methods:{
passToChild: function(){
this.$bus.$emit('passTo', this.check);
}
}
componentTwo.vue:
data:() => ({
content: "",
}),
mounted() {
this.$bus.$on('passTo', (content) => {
this.content = content;
})
}
复制代码
这即是BUS的用法。spa
上面是一些经常使用的组件之间通讯以及状态管理的方式,下一篇文章咱们将会来具体的学习vuex的内容,将会更加方便的管理咱们大型项目之中的状态内容。下章再见。prototype