vuex引入篇--vue組件間通訊

前言

vue雖然支持雙向綁定,可是組件之間總歸而言仍是單項的,因此咱們在這一片內容之中將會去簡單的瞭解和總結,咱們最日常的vue組件之間通訊是經過什麼樣的方式來的。vue

父子組件通訊。

父 --> 子:咱們經常使用的props屬性就是用來對父子組件進行內容的傳遞的。
vuex

父 --> 孫:bash

  • 這裏咱們要注意了,咱們能夠經過使用props屬性來傳遞。
  • vue爲咱們的vueComponent對象提供了$root和 $parent兩個屬性,分別指向的是根節點的vue對象和父組件的vueComponent對象。這個時候咱們經過這兩個對象來進行內容的操做。
  • vue同時爲咱們提供了依賴注入功能,經過在組件之中設置provide屬性,提供給其後代們以某一份數據或者方法來操做當前組件之中的狀態信息。子孫組建須要使用的時候只須要使用inject關鍵字進行內容的注入,而後咱們能夠經過this來調用注入的方法或者參數。代碼可見以下
父組件:
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呢,實際上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

相關文章
相關標籤/搜索