vue的8種通信方式

一、props / emit 父組件通過props的方式向子組件傳遞數(shù)據(jù)锐秦,而通過emit 子組件可以向父組件通信塘砸。

  1. 父組件向子組件傳值
    下面通過一個例子說明父組件如何向子組件傳遞數(shù)據(jù):在子組件article.vue中如何獲取父組件section.vue中的數(shù)據(jù)articles:['紅樓夢', '西游記','三國演義']
// section父組件
<template>
  <div class="section">
    <com-article :articles="articleList"></com-article>
  </div>
</template>
 
<script>
import comArticle from "./test/article.vue";
export default {
  name: "HelloWorld",
  components: { comArticle },
  data() {
    return {
      articleList: ["紅樓夢", "西游記", "三國演義"]
    };
  }
};
</script>
// 子組件 article.vue
<template>
  <div>
    <span v-for="(item, index) in articles" :key="index">{{item}}</span>
  </div>
</template>
 
<script>
export default {
  props: ["articles"]
};
</script>

總結: prop 只可以從上一級組件傳遞到下一級組件(父子組件),即所謂的單向數(shù)據(jù)流蕊肥。而且 prop 只讀薪铜,不可被修改吼渡,所有修改都會失效并警告容为。

  1. 子組件向父組件傳值
    對于emit 我自己的理解是這樣的:emit綁定一個自定義事件, 當這個語句被執(zhí)行時, 就會將參數(shù)arg傳遞給父組件,父組件通過v-on監(jiān)聽并接收參數(shù)。 通過一個例子,說明子組件如何向父組件傳遞數(shù)據(jù)坎背。
    在上個例子的基礎上, 點擊頁面渲染出來的ariticle的item, 父組件中顯示在數(shù)組中的下標
// 父組件中
<template>
  <div class="section">
    <com-article :articles="articleList" @onEmitIndex="onEmitIndex"></com-article>
    <p>{{currentIndex}}</p>
  </div>
</template>
 
<script>
import comArticle from "./test/article.vue";
export default {
  name: "HelloWorld",
  components: { comArticle },
  data() {
    return {
      currentIndex: -1,
      articleList: ["紅樓夢", "西游記", "三國演義"]
    };
  },
  methods: {
    onEmitIndex(idx) {
      this.currentIndex = idx;
    }
  }
};
</script>
// 在子組件中
<template>
  <div>
    <div v-for="(item, index) in articles" :key="index" @click="emitIndex(index)">{{item}}</div>
  </div>
</template>
 
<script>
export default {
  props: ["articles"],
  methods: {
    emitIndex(index) {
      this.$emit("onEmitIndex", index);
    }
  }
};
</script>

二替劈、 children /parent

image.png

上面這張圖片是vue官方的解釋,通過parent和children就可以訪問組件的實例得滤,拿到實例代表什么陨献?代表可以訪問此組件的所有方法和data。接下來就是怎么實現(xiàn)拿到指定組件的實例懂更。

使用方法

// 父組件中
<template>
  <div class="hello_world">
    <div>{{msg}}</div>
    <com-a></com-a>
    <button @click="changeA">點擊改變子組件值</button>
  </div>
</template>
 
<script>
import ComA from "./test/comA.vue";
export default {
  name: "HelloWorld",
  components: { ComA },
  data() {
    return {
      msg: "Welcome"
    };
  },

  methods: {
    changeA() {
      // 獲取到子組件A
      this.$children[0].messageA = "this is new value";
    }
  }
};
</script>
// 子組件中
<template>
  <div class="com_a">
    <span>{{messageA}}</span>
    <p>獲取父組件的值為: {{parentVal}}</p>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      messageA: "this is old"
    };
  },
  computed: {
    parentVal() {
      return this.$parent.msg;
    }
  }
};
</script>

要注意邊界情況眨业,如在#app上拿parent得到的是new Vue()的實例,在這實例上再拿parent得到的是undefined沮协,而在最底層的子組件拿children是個空數(shù)組龄捡。也要注意得到parent和children的值不一樣,children 的值是數(shù)組慷暂,而$parent是個對象

總結
上面兩種方式用于父子組件之間的通信聘殖, 而使用props進行父子組件通信更加普遍; 二者皆不能用于非父子組件之間的通信。
三行瑞、provide/ inject
概念:
provide/ inject 是vue2.2.0新增的api, 簡單來說就是父組件中通過provide來提供變量, 然后再子組件中通過inject來注入變量就斤。

注意: 這里不論子組件嵌套有多深, 只要調(diào)用了inject 那么就可以注入provide中的數(shù)據(jù),而不局限于只能從當前父組件的props屬性中回去數(shù)據(jù)

舉例驗證
接下來就用一個例子來驗證上面的描述:
假設有三個組件: A.vue蘑辑、B.vue、C.vue 其中 C是B的子組件坠宴,B是A的子組件

// A.vue
 
<template>
  <div>
    <comB></comB>
  </div>
</template>
 
<script>
import comB from "../components/test/comB.vue";
export default {
  name: "A",
  provide: {
    for: "demo"
  },
  components: {
    comB
  }
};
</script>
// B.vue
 
<template>
  <div>
    {{demo}}
    <comC></comC>
  </div>
</template>
 
<script>
import comC from "../components/test/comC.vue";
export default {
  name: "B",
  inject: ["for"],
  data() {
    return {
      demo: this.for
    };
  },
  components: {
    comC
  }
};
</script>
// C.vue
<template>
  <div>{{demo}}</div>
</template>
 
<script>
export default {
  name: "C",
  inject: ["for"],
  data() {
    return {
      demo: this.for
    };
  }
};
</script>

四洋魂、ref / refs

ref:如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素喜鼓;如果用在子組件上副砍,引用就指向組件實例,可以通過實例直接調(diào)用組件的方法或訪問數(shù)據(jù)庄岖, 我們看一個ref 來訪問組件的例子:

// 子組件 A.vue
export default {
  data() {
    return {
      name: "Vue.js"
    };
  },
  methods: {
    sayHello() {
      console.log("hello");
    }
  }
};
// 父組件 app.vue
<template>
  <component-a ref="comA"></component-a>
</template>
<script>
export default {
  mounted() {
    const comA = this.$refs.comA;
    console.log(comA.name); // Vue.js
    comA.sayHello(); // hello
  }
};
</script>

五豁翎、event/Bus

eventBus 又稱為事件總線,在vue中可以使用它來作為溝通橋梁的概念, 就像是所有組件共用相同的事件中心隅忿,可以向該中心注冊發(fā)送事件或接收事件心剥, 所以組件都可以通知其他組件。

eventBus也有不方便之處, 當項目較大,就容易造成難以維護的災難

在Vue的項目中怎么使用eventBus來實現(xiàn)組件之間的數(shù)據(jù)通信呢?具體通過下面幾個步驟
1. 初始化
首先需要創(chuàng)建一個事件總線并將其導出, 以便其他模塊可以使用或者監(jiān)聽它.

// event-bus.js
import Vue from 'vue'
export const EventBus = new Vue()

2. 發(fā)送事件
假設你有兩個組件: additionNum 和 showNum, 這兩個組件可以是兄弟組件也可以是父子組件背桐;這里我們以兄弟組件為例:

<template>
  <div>
    <show-num-com></show-num-com>
    <addition-num-com></addition-num-com>
  </div>
</template>
 
<script>
import showNumCom from "./showNum.vue";
import additionNumCom from "./additionNum.vue";
export default {
  components: { showNumCom, additionNumCom }
};
</script>
// addtionNum.vue 中發(fā)送事件
 
<template>
  <div>
    <button @click="additionHandle">+加法器</button>
  </div>
</template>
 
<script>
import { EventBus } from "./event-bus.js";
console.log(EventBus);
export default {
  data() {
    return {
      num: 1
    };
  },

  methods: {
    additionHandle() {
      EventBus.$emit("addition", {
        num: this.num++
      });
    }
  }
};
</script>

3. 接收事件

// showNum.vue 中接收事件
 
<template>
 <div>計算和: {{count}}</div>
</template>
 
<script>
import { EventBus } from './event-bus.js'
export default {
 data() {
  return {
   count: 0
  }
 },
 mounted() {
  EventBus.$on('addition', param => {
   this.count = this.count + param.num;
  })
 }
}
</script>

這樣就實現(xiàn)了在組件addtionNum.vue中點擊相加按鈕, 在showNum.vue中利用傳遞來的 num 展示求和的結果.
4. 移除事件監(jiān)聽者

如果想移除事件的監(jiān)聽, 可以像下面這樣操作

import { eventBus } from'event-bus.js'
EventBus.$off('addition', {})

六优烧、Vuex

1. Vuex介紹

Vuex 是一個專為 Vue.js 應用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲管理應用的所有組件的狀態(tài)链峭,并以相應的規(guī)則保證狀態(tài)以一種可預測的方式發(fā)生變化.
Vuex 解決了多個視圖依賴于同一狀態(tài)和來自不同視圖的行為需要變更同一狀態(tài)的問題畦娄,將開發(fā)者的精力聚焦于數(shù)據(jù)的更新而不是數(shù)據(jù)在組件之間的傳遞上

2. Vuex各個模塊

  • state:用于數(shù)據(jù)的存儲,是store中的唯一數(shù)據(jù)源
  • getters:如vue中的計算屬性一樣,基于state數(shù)據(jù)的二次包裝熙卡,常用于數(shù)據(jù)的篩選和多個數(shù)據(jù)的相關性計算
  • mutations:類似函數(shù)杖刷,改變state數(shù)據(jù)的唯一途徑,且不能用于處理異步事件
  • actions:類似于mutation驳癌,用于提交mutation來改變狀態(tài)滑燃,而不直接變更狀態(tài),可以包含任意異步操作
  • modules:類似于命名空間喂柒,用于項目中將各個模塊的狀態(tài)分開定義和操作不瓶,便于維護

3. Vuex實例應用

// 父組件
 
<template>
  <div id="app">
    <ChildA />
    <ChildB />
  </div>
</template>
 
<script>
import ChildA from "./components/ChildA"; // 導入A組件
import ChildB from "./components/ChildB"; // 導入B組件

export default {
  name: "App",
  components: { ChildA, ChildB } // 注冊A、B組件
};
</script>
// 子組件childA
 
<template>
  <div id="childA">
    <h1>我是A組件</h1>
    <button @click="transform">點我讓B組件接收到數(shù)據(jù)</button>
    <p>因為你點了B灾杰,所以我的信息發(fā)生了變化:{{BMessage}}</p>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      AMessage: "Hello蚊丐,B組件,我是A組件"
    };
  },
  computed: {
    BMessage() {
      // 這里存儲從store里獲取的B組件的數(shù)據(jù)
      return this.$store.state.BMsg;
    }
  },
  methods: {
    transform() {
      // 觸發(fā)receiveAMsg艳吠,將A組件的數(shù)據(jù)存放到store里去
      this.$store.commit("receiveAMsg", {
        AMsg: this.AMessage
      });
    }
  }
};
</script>
// 子組件 childB
 
<template>
  <div id="childB">
    <h1>我是B組件</h1>
    <button @click="transform">點我讓A組件接收到數(shù)據(jù)</button>
    <p>因為你點了A麦备,所以我的信息發(fā)生了變化:{{AMessage}}</p>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      BMessage: "Hello,A組件昭娩,我是B組件"
    };
  },
  computed: {
    AMessage() {
      // 這里存儲從store里獲取的A組件的數(shù)據(jù)
      return this.$store.state.AMsg;
    }
  },
  methods: {
    transform() {
      // 觸發(fā)receiveBMsg凛篙,將B組件的數(shù)據(jù)存放到store里去
      this.$store.commit("receiveBMsg", {
        BMsg: this.BMessage
      });
    }
  }
};
</script>

vuex的store,js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
 // 初始化A和B組件的數(shù)據(jù),等待獲取
 AMsg: '',
 BMsg: ''
}
 
const mutations = {
 receiveAMsg(state, payload) {
  // 將A組件的數(shù)據(jù)存放于state
  state.AMsg = payload.AMsg
 },
 receiveBMsg(state, payload) {
  // 將B組件的數(shù)據(jù)存放于state
  state.BMsg = payload.BMsg
 }
}
 
export default new Vuex.Store({
 state,
 mutations
})

七栏渺、localStorage / sessionStorage

這種通信比較簡單,缺點是數(shù)據(jù)和狀態(tài)比較混亂,不太容易維護呛梆。
通過window.localStorage.getItem(key)獲取數(shù)據(jù)
通過window.localStorage.setItem(key,value)存儲數(shù)據(jù)

注意用JSON.parse() / JSON.stringify() 做數(shù)據(jù)格式轉換
localStorage / sessionStorage可以結合vuex, 實現(xiàn)數(shù)據(jù)的持久保存,同時使用vuex解決數(shù)據(jù)和狀態(tài)混亂問題.

attrs與listeners

現(xiàn)在我們來討論一種情況, 我們一開始給出的組件關系圖中A組件與D組件是隔代關系磕诊, 那它們之前進行通信有哪些方式呢填物?

使用props綁定來進行一級一級的信息傳遞, 如果D組件中狀態(tài)改變需要傳遞數(shù)據(jù)給A, 使用事件系統(tǒng)一級級往上傳遞
使用eventBus,這種情況下還是比較適合使用, 但是碰到多人合作開發(fā)時, 代碼維護性較低, 可讀性也低
使用Vuex來進行數(shù)據(jù)管理, 但是如果僅僅是傳遞數(shù)據(jù), 而不做中間處理,使用Vuex處理感覺有點大材小用了.
在vue2.4中,為了解決該需求霎终,引入了attrs 和listeners 滞磺, 新增了inheritAttrs 選項。 在版本2.4以前莱褒,默認情況下,父作用域中不作為 prop 被識別 (且獲取) 的特性綁定 (class 和 style 除外)击困,將會“回退”且作為普通的HTML特性應用在子組件的根元素上。接下來看一個跨級通信的例子:

// app.vue
// index.vue

<template>
  <div>
    <child-com1 :name="name" :age="age" :gender="gender" :height="height" title="程序員成長指北"></child-com1>
  </div>
</template>
<script>
const childCom1 = () => import("./childCom1.vue");
export default {
  components: { childCom1 },
  data() {
    return {
      name: "zhang",
      age: "18",
      gender: "女",
      height: "158"
    };
  }
};
</script>
// childCom1.vue
<template class="border">
  <div>
    <p>name: {{ name}}</p>
    <p>childCom1的$attrs: {{ $attrs }}</p>
    <child-com2 v-bind="$attrs"></child-com2>
  </div>
</template>
<script>
const childCom2 = () => import("./childCom2.vue");
export default {
  components: {
    childCom2
  },
  inheritAttrs: false, // 可以關閉自動掛載到組件根元素上的沒有在props聲明的屬性
  props: {
    name: String // name作為props屬性綁定
  },
  created() {
    console.log(this.$attrs);
    // { "age": "18", "gender": "女", "height": "158", "title": "程序員成長指北" }
  }
};
</script>
// childCom2.vue
<template>
  <div class="border">
    <p>age: {{ age}}</p>
    <p>childCom2: {{ $attrs }}</p>
  </div>
</template>
<script>
export default {
  inheritAttrs: false,
  props: {
    age: String
  },
  created() {
    console.log(this.$attrs);
    // { "gender": "女", "height": "158", "title": "程序員成長指北" }
  }
};
</script>

總結
常見使用場景可以分為三類:

父子組件通信: props; parent /children; provide / inject ; ref ; attrs /listeners
兄弟組件通信: eventBus ; vuex
跨級通信: eventBus广凸;Vuex阅茶;provide / inject 、attrs /listeners
好了谅海,以上就是這篇文章的全部內(nèi)容了目派,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持胁赢。

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末企蹭,一起剝皮案震驚了整個濱河市白筹,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌谅摄,老刑警劉巖徒河,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異送漠,居然都是意外死亡顽照,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進店門闽寡,熙熙樓的掌柜王于貴愁眉苦臉地迎上來代兵,“玉大人,你說我怎么就攤上這事爷狈≈灿埃” “怎么了?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵涎永,是天一觀的道長思币。 經(jīng)常有香客問我,道長羡微,這世上最難降的妖魔是什么谷饿? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮妈倔,結果婚禮上博投,老公的妹妹穿的比我還像新娘。我一直安慰自己盯蝴,他們只是感情好贬堵,可當我...
    茶點故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著结洼,像睡著了一般。 火紅的嫁衣襯著肌膚如雪叉跛。 梳的紋絲不亂的頭發(fā)上松忍,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天,我揣著相機與錄音筷厘,去河邊找鬼鸣峭。 笑死,一個胖子當著我的面吹牛酥艳,可吹牛的內(nèi)容都是我干的摊溶。 我是一名探鬼主播,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼充石,長吁一口氣:“原來是場噩夢啊……” “哼莫换!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤拉岁,失蹤者是張志新(化名)和其女友劉穎坷剧,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體喊暖,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡惫企,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了陵叽。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片狞尔。...
    茶點故事閱讀 40,040評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖巩掺,靈堂內(nèi)的尸體忽然破棺而出偏序,到底是詐尸還是另有隱情,我是刑警寧澤锌半,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布禽车,位于F島的核電站,受9級特大地震影響刊殉,放射性物質發(fā)生泄漏殉摔。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一记焊、第九天 我趴在偏房一處隱蔽的房頂上張望逸月。 院中可真熱鬧,春花似錦遍膜、人聲如沸碗硬。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽恩尾。三九已至,卻和暖如春挽懦,著一層夾襖步出監(jiān)牢的瞬間翰意,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工信柿, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留冀偶,地道東北人。 一個月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓渔嚷,卻偏偏與公主長得像进鸠,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子形病,可洞房花燭夜當晚...
    茶點故事閱讀 44,979評論 2 355