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