溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Vue組件的通信方式有哪些

發(fā)布時(shí)間:2023-04-20 09:28:31 來源:億速云 閱讀:96 作者:iii 欄目:編程語言

這篇文章主要介紹“Vue組件的通信方式有哪些”,在日常操作中,相信很多人在Vue組件的通信方式有哪些問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Vue組件的通信方式有哪些”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

組件是 vue.js最強(qiáng)大的功能之一,而組件實(shí)例的作用域是相互獨(dú)立的,這就意味著不同組件之間的數(shù)據(jù)無法相互引用。 vue組件間的傳值方式多種多樣,并不局限于父子傳值、事件傳值這些。

provide / inject

這一組選項(xiàng)需要一起使用,允許一個(gè)祖先組件向其所有的后代組件注入一個(gè)依賴,不論組件層級(jí)有多深,并在其上下游關(guān)系成立的時(shí)間里始終生效。

// provide 選項(xiàng)應(yīng)該是一個(gè)對象或返回一個(gè)對象的函數(shù)
// inject 選項(xiàng)應(yīng)該是:一個(gè)字符串?dāng)?shù)組,或一個(gè)對象,對象的 key 是本地的綁定名

// 父級(jí)組件提供 'foo'
var Provider = {
  provide: {
    foo: 'bar'
  },
  // ...
}

// 子組件注入 'foo' (數(shù)組形式)
var Child = {
  inject: ['foo'], 
  created () {
    console.log(this.foo) // => "bar"
  }
  // ...
}

或 (對象形式)
var Child = {
  inject: {
  	foo: { 
  		from: 'bar', // 可選
  		default: 'self defined content' // 默認(rèn)值
  	}
  }, 
  created () {
    console.log(this.foo) // => "bar"
  }
  // ...
}

需要注意的是: Vue 2.2.1 或更高版本中,inject注入的值會(huì)在 props 和 data 初始化之前得到

// 使用一個(gè)注入的值作為數(shù)據(jù)(data)的入口 或者 屬性(props)的默認(rèn)值
const Child = {
  inject: ['foo'],
  data () {
    return {
      bar: this.foo // 輸出bar的值與foo相同
    }
  }
}

const Child = {
  inject: ['foo'],
  props: {
    bar: {
      default () {
        return this.foo
      }
    }
  }
}

-----------------------------------------------------------------------------------------------
// 注入可以通過設(shè)置默認(rèn)值使其變成可選項(xiàng)
const Child = {
  inject: {
    foo: { // 注意: 此處key值必須是父組件中provide的屬性的key
      from: 'bar', // 屬性是在可用的注入內(nèi)容中搜索用的 key (字符串或 Symbol), data或者props中的可搜索值
      default: 'foo' // 屬性是降級(jí)情況下使用的 value, 默認(rèn)值為 ‘foo’
    }
  }
}

// 與 prop 的默認(rèn)值類似
const Child = {
  inject: {
    foo: {
      from: 'bar',
      default: () => [1, 2, 3] // 默認(rèn)值為引用類型時(shí),需要使用一個(gè)工廠方法返回對象
    }
  }
}

簡介Vue2.2.0新增API,這對選項(xiàng)需要一起使用,以允許一個(gè)祖先組件向其所有子孫后代注入一個(gè)依賴,不論組件層次有多深,并在起上下游關(guān)系成立的時(shí)間里始終生效。一言而蔽之:祖先組件中通過provider來提供變量,然后在子孫組件中通過inject來注入變量。 provide / inject API 主要解決了跨級(jí)組件間的通信問題,不過它的使用場景,主要是子組件獲取上級(jí)組件的狀態(tài),跨級(jí)組件間建立了一種主動(dòng)提供與依賴注入的關(guān)系。

案例假設(shè)有兩個(gè)組件: A.vue 和 B.vue,B 是 A 的子組件

A.vue

export default {
  provide: {
    name: '浪里行舟'
  }
}

B.vue

export default {
  inject: ['name'],
  mounted () {
    console.log(this.name);  // 浪里行舟
  }
}

可以看到,在 A.vue 里,我們設(shè)置了一個(gè) provide: name,值為 浪里行舟,它的作用就是將 name 這個(gè)變量提供給它的所有子組件。而在 B.vue 中,通過 inject 注入了從 A 組件中提供的 name 變量,那么在組件 B 中,就可以直接通過 this.name 訪問這個(gè)變量了,它的值也是 浪里行舟。這就是 provide / inject API 最核心的用法。

需要注意的是:provide 和 inject 綁定并不是可響應(yīng)的。這是刻意為之的。然而,如果你傳入了一個(gè)可監(jiān)聽的對象,那么其對象的屬性還是可響應(yīng)的----vue官方文檔 所以,上面 A.vue 的 name 如果改變了,B.vue 的 this.name 是不會(huì)改變的,仍然是 浪里行舟。

provide與inject 怎么實(shí)現(xiàn)數(shù)據(jù)響應(yīng)式

一般來說,有兩種辦法:

  • provide祖先組件的實(shí)例,然后在子孫組件中注入依賴,這樣就可以在子孫組件中直接修改祖先組件的實(shí)例的屬性,不過這種方法有個(gè)缺點(diǎn)就是這個(gè)實(shí)例上掛載很多沒有必要的東西比如props,methods

  • 使用2.6最新API Vue.observable 優(yōu)化響應(yīng)式 provide(推薦)

我們來看個(gè)例子:孫組件D、E和F獲取A組件傳遞過來的color值,并能實(shí)現(xiàn)數(shù)據(jù)響應(yīng)式變化,即A組件的color變化后,組件D、E、F不會(huì)跟著變(核心代碼如下:)

A 組件

<div>
      <h2>A 組件</h2>
      <button @click="() => changeColor()">改變color</button>
      <ChildrenB />
      <ChildrenC />
</div>
......
  data() {
    return {
      color: "blue"
    };
  },
  // provide() {
  //   return {
  //     theme: {
  //       color: this.color //這種方式綁定的數(shù)據(jù)并不是可響應(yīng)的
  //     } // 即A組件的color變化后,組件D、E、F不會(huì)跟著變
  //   };
  // },
  provide() {
    return {
      theme: this//方法一:提供祖先組件的實(shí)例
    };
  },
  methods: {
    changeColor(color) {
      if (color) {
        this.color = color;
      } else {
        this.color = this.color === "blue" ? "red" : "blue";
      }
    }
  }
  // 方法二:使用2.6最新API Vue.observable 優(yōu)化響應(yīng)式 provide
  // provide() {
  //   this.theme = Vue.observable({
  //     color: "blue"
  //   });
  //   return {
  //     theme: this.theme
  //   };
  // },
  // methods: {
  //   changeColor(color) {
  //     if (color) {
  //       this.theme.color = color;
  //     } else {
  //       this.theme.color = this.theme.color === "blue" ? "red" : "blue";
  //     }
  //   }
  // }

F 組件

<template functional>
  <div class="border2">
    <h4 :style="{ color: injections.theme.color }">F 組件</h4>
  </div>
</template>
<script>
export default {
  inject: {
    theme: {
      //函數(shù)式組件取值不一樣
      default: () => ({})
    }
  }
};
</script>

雖說provide 和 inject 主要為高階插件/組件庫提供用例,但如果你能在業(yè)務(wù)中熟練運(yùn)用,可以達(dá)到事半功倍的效果!

props (父傳子)

// 創(chuàng)建組件
Vue.component('props-demo-advanced', {
  props: {
    age: {
      type: Number,
      default: 0
    }
  }
})

// 父組件中注冊和使用組件,并傳值
<props-demo-advanced :age="age"> </props-demo-advanced>

props/$emit父組件A通過props的方式向子組件B傳遞,B to A 通過在 B 組件中 $emit, A 組件中 v-on 的方式實(shí)現(xiàn)。案例 : 父組件向子組件傳值 下例說明父組件如何向子組件傳遞值:在子組件Users.vue中如何獲取父組件App.vue中的數(shù)據(jù) users:["Henry","Bucky","Emily"]

App.vue父組件

<template>
  <div id="app">
    <users v-bind:users="users"></users>//前者自定義名稱便于子組件調(diào)用,后者要傳遞數(shù)據(jù)名
  </div>
</template>
<script>
import Users from "./components/Users"
export default {
  name: 'App',
  data(){
    return{
      users:["Henry","Bucky","Emily"]
    }
  },
  components:{
    "users":Users
  }
}

users子組件

<template>
  <div class="hello">
    <ul>
      <li v-for="user in users">{{user}}</li>//遍歷傳遞過來的值,然后呈現(xiàn)到頁面
    </ul>
  </div>
</template>
<script>
export default {
  name: 'HelloWorld',
  props:{
    users:{           //這個(gè)就是父組件中子標(biāo)簽自定義名字
      type:Array,
      required:true
    }
  }
}
</script>

總結(jié):父組件通過props向下傳遞數(shù)據(jù)給子組件。:組件中的數(shù)據(jù)共有三種形式:data、props、computed

$emit(子傳父)

// 子組件Child, 負(fù)載payload可選
this.$emit('eventName', payload)

// 父組件 Parent
<Parent @evnetName="sayHi"></Parent>

案例 : 子組件向父組件傳值(通過事件形式) 下例說明子組件如何向父組件傳遞值:當(dāng)點(diǎn)擊“Vue.js Demo”后,子組件向父組件傳遞值,文字由原來的“傳遞的是一個(gè)值”變成“子向父組件傳值”,實(shí)現(xiàn)子組件向父組件值的傳遞。

子組件

<template>
  <header>
    <h2 @click="changeTitle">{{title}}</h2>//綁定一個(gè)點(diǎn)擊事件
  </header>
</template>
<script>
export default {
  name: 'app-header',
  data() {
    return {
      title:"Vue.js Demo"
    }
  },
  methods:{
    changeTitle() {
      this.$emit("titleChanged","子向父組件傳值");//自定義事件  傳遞值“子向父組件傳值”
    }
  }
}
</script>

父組件

<template>
  <div id="app">
    <app-header v-on:titleChanged="updateTitle" ></app-header>//與子組件titleChanged自定義事件保持一致
   // updateTitle($event)接受傳遞過來的文字
    <h3>{{title}}</h3>
  </div>
</template>
<script>
import Header from "./components/Header"
export default {
  name: 'App',
  data(){
    return{
      title:"傳遞的是一個(gè)值"
    }
  },
  methods:{
    updateTitle(e){   //聲明這個(gè)函數(shù)
      this.title = e;
    }
  },
  components:{
   "app-header":Header,
  }
}
</script>

總結(jié):子組件通過events給父組件發(fā)送消息,實(shí)際上就是子組件把自己的數(shù)據(jù)發(fā)送到父組件。

$emit/$on這種方法通過一個(gè)空的Vue實(shí)例作為中央事件總線(事件中心),用它來觸發(fā)事件和監(jiān)聽事件,巧妙而輕量地實(shí)現(xiàn)了任何組件間的通信,包括父子、兄弟、跨級(jí)。當(dāng)我們的項(xiàng)目比較大時(shí),可以選擇更好的狀態(tài)管理解決方案vuex。

1.具體實(shí)現(xiàn)方式:

var Event=new Vue();
Event.$emit(事件名,數(shù)據(jù));
Event.$on(事件名,data => {});

案例 : 假設(shè)兄弟組件有三個(gè),分別是A、B、C組件,C組件如何獲取A或者B組件的數(shù)據(jù)

<div id="itany">
	<my-a></my-a>
	<my-b></my-b>
	<my-c></my-c>
</div>
<template id="a">
  <div>
    <h4>A組件:{{name}}</h4>
    <button @click="send">將數(shù)據(jù)發(fā)送給C組件</button>
  </div>
</template>
<template id="b">
  <div>
    <h4>B組件:{{age}}</h4>
    <button @click="send">將數(shù)組發(fā)送給C組件</button>
  </div>
</template>
<template id="c">
  <div>
    <h4>C組件:{{name}},{{age}}</h4>
  </div>
</template>
<script>
var Event = new Vue();//定義一個(gè)空的Vue實(shí)例
var A = {
	template: '#a',
	data() {
	  return {
	    name: 'tom'
	  }
	},
	methods: {
	  send() {
	    Event.$emit('data-a', this.name);
	  }
	}
}
var B = {
	template: '#b',
	data() {
	  return {
	    age: 20
	  }
	},
	methods: {
	  send() {
	    Event.$emit('data-b', this.age);
	  }
	}
}
var C = {
	template: '#c',
	data() {
	  return {
	    name: '',
	    age: ""
	  }
	},
	mounted() {//在模板編譯完成后執(zhí)行
	Event.$on('data-a',name => {
	     this.name = name;//箭頭函數(shù)內(nèi)部不會(huì)產(chǎn)生新的this,這邊如果不用=>,this指代Event
	})
	Event.$on('data-b',age => {
	     this.age = age;
	})
	}
}
var vm = new Vue({
	el: '#itany',
	components: {
	  'my-a': A,
	  'my-b': B,
	  'my-c': C
	}
});	
</script>

$on 監(jiān)聽了自定義事件 data-a和data-b,因?yàn)橛袝r(shí)不確定何時(shí)會(huì)觸發(fā)事件,一般會(huì)在 mounted 或 created 鉤子中來監(jiān)聽。

eventBus(全局創(chuàng)建Vue實(shí)例)

進(jìn)行事件監(jiān)聽和數(shù)據(jù)傳遞。同時(shí)vuex也是基于這個(gè)原理實(shí)現(xiàn)的

// 三步使用
// 1. 創(chuàng)建
window.$bus = new Vue()

// 2. 注冊事件
window.$bus.$on('user_task_change', (payload) => {
  console.log('事件觸發(fā)')
})

// 3. 觸發(fā)
window.$bus.$emit('user_task_change', payload)

vuex (狀態(tài)管理)

1.簡要介紹Vuex原理Vuex實(shí)現(xiàn)了一個(gè)單向數(shù)據(jù)流,在全局擁有一個(gè)State存放數(shù)據(jù),當(dāng)組件要更改State中的數(shù)據(jù)時(shí),必須通過Mutation進(jìn)行,Mutation同時(shí)提供了訂閱者模式供外部插件調(diào)用獲取State數(shù)據(jù)的更新。而當(dāng)所有異步操作(常見于調(diào)用后端接口異步獲取更新數(shù)據(jù))或批量的同步操作需要走Action,但Action也是無法直接修改State的,還是需要通過Mutation來修改State的數(shù)據(jù)。最后,根據(jù)State的變化,渲染到視圖上。

2.簡要介紹各模塊在流程中的功能

  • Vue Components:Vue組件。HTML頁面上,負(fù)責(zé)接收用戶操作等交互行為,執(zhí)行dispatch方法觸發(fā)對應(yīng)action進(jìn)行回應(yīng)。

  • dispatch:操作行為觸發(fā)方法,是唯一能執(zhí)行action的方法。

  • actions:操作行為處理模塊,由組件中的$store.dispatch('action 名稱', data1)來觸發(fā)。然后由commit()來觸發(fā)mutation的調(diào)用 , 間接更新 state。負(fù)責(zé)處理Vue Components接收到的所有交互行為。包含同步/異步操作,支持多個(gè)同名方法,按照注冊的順序依次觸發(fā)。向后臺(tái)API請求的操作就在這個(gè)模塊中進(jìn)行,包括觸發(fā)其他action以及提交mutation的操作。該模塊提供了Promise的封裝,以支持action的鏈?zhǔn)接|發(fā)。

  • commit:狀態(tài)改變提交操作方法。對mutation進(jìn)行提交,是唯一能執(zhí)行mutation的方法。

  • mutations:狀態(tài)改變操作方法,由actions中的commit('mutation 名稱')來觸發(fā)。是Vuex修改state的唯一推薦方法。該方法只能進(jìn)行同步操作,且方法名只能全局唯一。操作之中會(huì)有一些hook暴露出來,以進(jìn)行state的監(jiān)控等。

  • state:頁面狀態(tài)管理容器對象。集中存儲(chǔ)Vue components中data對象的零散數(shù)據(jù),全局唯一,以進(jìn)行統(tǒng)一的狀態(tài)管理。頁面顯示所需的數(shù)據(jù)從該對象中進(jìn)行讀取,利用Vue的細(xì)粒度數(shù)據(jù)響應(yīng)機(jī)制來進(jìn)行高效的狀態(tài)更新。

  • getters:state對象讀取方法。圖中沒有單獨(dú)列出該模塊,應(yīng)該被包含在了render中,Vue Components通過該方法讀取全局state對象。

3.Vuex與localStoragevuex 是 vue 的狀態(tài)管理器,存儲(chǔ)的數(shù)據(jù)是響應(yīng)式的。但是并不會(huì)保存起來,刷新之后就回到了初始狀態(tài),具體做法應(yīng)該在vuex里數(shù)據(jù)改變的時(shí)候把數(shù)據(jù)拷貝一份保存到localStorage里面,刷新之后,如果localStorage里有保存的數(shù)據(jù),取出來再替換store里的state。

let defaultCity = "上海"
try {   // 用戶關(guān)閉了本地存儲(chǔ)功能,此時(shí)在外層加個(gè)try...catch
  if (!defaultCity){
    defaultCity = JSON.parse(window.localStorage.getItem('defaultCity'))
  }
}catch(e){}
export default new Vuex.Store({
  state: {
    city: defaultCity
  },
  mutations: {
    changeCity(state, city) {
      state.city = city
      try {
      window.localStorage.setItem('defaultCity', JSON.stringify(state.city));
      // 數(shù)據(jù)改變的時(shí)候把數(shù)據(jù)拷貝一份保存到localStorage里面
      } catch (e) {}
    }
  }
})

這里需要注意的是:由于vuex里,我們保存的狀態(tài),都是數(shù)組,而localStorage只支持字符串,所以需要用JSON轉(zhuǎn)換:

JSON.stringify(state.subscribeList);   // array -> string
JSON.parse(window.localStorage.getItem("subscribeList"));    // string -> array

Vuex文件 案例 : 目錄結(jié)構(gòu)如下:

Vue組件的通信方式有哪些

其中vuex相關(guān)的三個(gè)文件counts.js、 index.js、 operate.js,內(nèi)容如下:

Vue組件的通信方式有哪些

index.js

import Vue from 'vue'
import Vuex from 'vuex'
import counter from './counter.js'
import operate from './operate.js'
Vue.use(Vuex)

const state = {
  name: 'zhaoyh'
}

const getters = {
  getName (state) {
    return state.name
  }
}

const mutations = {
  changeName (state, payload) {
    state.name = `${state.name} ${payload}`
  }
}

const actions = {
  changeNameAsync (context, payload) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        context.commit('changeName', payload)
      }, 1000)
    })
  }
}

const store = new Vuex.Store({
  state,
  getters,
  mutations,
  actions,
  modules: {
    counter,
    operate
  }
})

export default store

counter.js

// 模塊內(nèi)方法調(diào)用本模塊內(nèi)的方法和數(shù)據(jù)
const state = {
  counterName: 'module > counter > zhaoyh'
}
const getters = {
  // state, getters: 本模塊內(nèi)的state, getters
  // rootState, rootGetters: 根模塊/根節(jié)點(diǎn)內(nèi)的state, getters
  // rootState, rootGetters: 同時(shí)也包括各個(gè)模塊中的state 和 getters
  getCounterName (state, getters, rootState, rootGetters) {
    // rootState.name
    // rootState.counter.counterName
    // rootState.operate.operateName
    console.log(rootState)
    // rootGetters.getName, 
    // rootGetters['counter/getCounterName']
    // rootGetters['operate/getOperateName']
    console.log(rootGetters)
    return state.counterName
  }
}
const mutations = {
  changeCounterName (state, payload) {
    state.counterName = `${state.counterName} ${payload}`
  }
}
const actions = {
  // context 與 store 實(shí)例具有相同方法和屬性 ------  important!?。?
  // context 包括: dispatch, commit, state, getters, rootState, rootGetters
  changeCounterNameAsync (context, payload) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {context.commit('changeCounterName', payload)}, 1000)
    })
  }
}
export default {
  // 注意此處是namespaced,而不是namespace,
  // 寫錯(cuò)的話程序不會(huì)報(bào)錯(cuò),vuex靜默無法正常執(zhí)行
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}

operate.js

// 模塊內(nèi)方法調(diào)用和獲取本模塊之外的方法和數(shù)據(jù)
const state = {
  operateName: 'module > operate > zhaoyh'
}
// 如果你希望使用全局 state 和 getter
// rootState 和 rootGetter 會(huì)作為第三和第四參數(shù)傳入
// 也會(huì)通過 context 對象的屬性傳入 action
const getters = {
  // state, getters: 本模塊內(nèi)的state, getters
  // rootState, rootGetters: 根模塊/根節(jié)點(diǎn)內(nèi)的state, getters, 包括各個(gè)模塊中的state 和 getters
  getOperateName (state, getters, rootState, rootGetters) {
    return state.operateName
  }
}
const mutations = {
  operateChangeCounterName (state, payload) {
    state.counterName = `${state.counterName} ${payload}`
  }
}
// 如果你希望使用全局 state 和 getter,
// 也會(huì)通過 context 對象的屬性傳入 action
const actions = {
  // context 與 store 實(shí)例具有相同方法和屬性---- ??!important!??!
  // context 包括:
  // dispatch, commit, state, getters, rootState, rootGetters
  operateChangeCounterNameAsync (context, payload) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
	    /*
	      * 若需要在全局命名空間內(nèi)分發(fā) action 或提交 mutation,
	      * 將 {root: true} 作為第三參數(shù)傳給 dispatch 或 commit 即可
	    */
	      context.commit('counter/changeCounterName', payload, { root: true })
	      // 或 context.dispatch('counter/changeCounterNameAsync', null, { root: true })
      }, 1000)
    })
  }
}
export default {
  // 注意此處是namespaced,而不是namespace,
  // 寫錯(cuò)的話程序不會(huì)報(bào)錯(cuò),vuex靜默無法正常執(zhí)行
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}

vuex屬性、方法的引用方式: common-operate.vue

<template>
  <div>
    <h3>{{title}}</h3>
    <ul>
      <li>name: {{name}}</li>
      <li>getName: {{getName}}</li>
      <li><button @click="changeName('lastName')">Mutation操作</button></li>
      <li><button @click="changeNameAsync('lastName')">Action操作</button></li>
    </ul>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'
export default {
  data () {
    return {
      title: 'vuex常規(guī)操作1'
    }
  },
  computed: {
    ...mapState(['name']),
    ...mapGetters(['getName'])
  },
  methods: {
    ...mapMutations(['changeName']),
    ...mapActions(['changeNameAsync'])
  }
}
</script>

<style scoped>
ul, li{
  padding: 0;
  margin: 0;
  padding: 8px 15px;
}
</style>

common-operate2.vue

<template>
  <div>
    <h3>{{title}}</h3>
    <ul>
      <li>name: {{name}}</li>
      <li>getName: {{getName}}</li>
      <li><button @click="changeName('lastName')">Mutation操作</button></li>
      <li><button @click="changeNameAsync('lastName')">Action操作</button></li>
    </ul>
  </div>
</template>

<script>
import { mapState, mapGetters } from 'vuex'
export default {
  data () {
    return {
      title: 'vuex常規(guī)操作2'
    }
  },
  computed: {
    ...mapState(['name']),
    ...mapGetters(['getName'])
  },
  methods: {
    // mutation
    changeName () {
      this.$store.commit('changeName', 'lastName')
    },
    // actions
    changeNameAsync () {
      this.$store.dispatch('changeNameAsync', 'lastName')
    }
  }
}
</script>

<style scoped>
ul, li{
  padding: 0;
  margin: 0;
  padding: 8px 15px;
}
</style>

module-operate.vue

<template>
  <div>
    <h3>{{title}}</h3>
    <ul>
      <li>name: {{counterName}}</li>
      <li>getName: {{getCounterName}}</li>
      <li><button @click="changeName('lastName')">Mutation操作</button></li>
      <li><button @click="changeNameAsync('lastName')">Action操作</button></li>
    </ul>
  </div>
</template>

<script>
import { mapState, mapGetters } from 'vuex'
export default {
  data () {
    return {
      title: '模塊的基本操作方法'
    }
  },
  computed: {
    ...mapState('counter', ['counterName']),
    ...mapGetters('counter', ['getCounterName'])
  },
  methods: {
    // mutation
    changeName () {
      this.$store.commit('counter/changeCounterName', 'lastName')
    },
    // actions
    changeNameAsync () {
      this.$store.dispatch('counter/changeCounterNameAsync', 'lastName')
    }
  }
}
</script>

<style scoped>
ul, li{
  padding: 0;
  margin: 0;
  padding: 8px 15px;
}
</style>

module-operate2.vue

<template>
  <div>
    <h3>{{title}}</h3>
    <ul>
      <li>name: {{counterName}}</li>
      <li>getName: {{getCounterName}}</li>
      <li><button @click="changeCounterName('lastName')">Mutation操作</button></li>
      <li><button @click="changeCounterNameAsync('lastName')">Action操作</button></li>
      <li><button @click="rename('rename')">Action操作</button></li>
    </ul>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
export default {
  data () {
    return {
      title: '模塊內(nèi)方法調(diào)用本模塊內(nèi)內(nèi)的方法和數(shù)據(jù)'
    }
  },
  computed: {
    ...mapState('counter', ['counterName']),
    ...mapGetters('counter', ['getCounterName'])
  },
  methods: {
    ...mapMutations('counter', ['changeCounterName']),
    ...mapActions('counter', ['changeCounterNameAsync']),
    // 多模塊方法引入的方法名重命名
    ...mapActions('counter', {
      rename: 'changeCounterNameAsync'
    }),
    otherMethods () {
      console.log('繼續(xù)添加其他方法。')
    }
  }
}
</script>

<style scoped>
ul, li{
  padding: 0;
  margin: 0;
  padding: 8px 15px;
}
</style>

module-operate3.vue

<template>
  <div>
    <h3>{{title}}</h3>
    <ul>
      <li>name: {{counterName}}</li>
      <li>getName: {{getCounterName}}</li>
      <li><button @click="operateChangeCounterNameAsync('operate lastName')">Action操作</button></li>
    </ul>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
export default {
  data () {
    return {
      title: '模塊內(nèi)方法調(diào)用和獲取本模塊之外的方法和數(shù)據(jù)'
    }
  },
  computed: {
    ...mapState('counter', ['counterName']),
    ...mapGetters('counter', ['getCounterName'])
  },
  methods: {
    ...mapMutations('operate', ['operateChangeCounterName']),
    ...mapActions('operate', ['operateChangeCounterNameAsync']),
    otherMethods () {
      console.log('繼續(xù)添加其他方法。')
    }
  }
}
</script>

<style scoped>
ul, li{
  padding: 0;
  margin: 0;
  padding: 8px 15px;
}
</style>

###### $parent / $children / $refs (獲取組件實(shí)例)$refs 獲取對應(yīng)組件實(shí)例,如果是原生dom,那么直接獲取的是該dom$parent / $children 該屬性只針對vue組件,獲取父/子組件實(shí)例 注: 節(jié)制地使用$parent $children - 它們的主要目的是作為訪問組件的應(yīng)急方法。更推薦用 props 和 events 實(shí)現(xiàn)父子組件通信

<!--  父組件,HelloWorld.vue-->
<template>
  <div class="hello">
    <ipc ref="ipcRef"></ipc>
  </div>
</template>

<script>
import ipc from './ipc'
export default {
  name: 'HelloWorld',
  data () {
    return {
      parentVal: 'parent content'
    }
  },
  mounted () {
    console.log(this.$refs.ipcRef.$data.child1) // "child1 content"
    console.log(this.$children[0].$data.child2) // "child2 content"
  },
  components: {
    ipc
  }
}
</script>
<!-- 子組件, ipc.vue-->
<template>
  <div>
  </div>
</template>

<script>
export default {
  props: {
  },
  data () {
    return {
      child1: 'child1 content',
      child2: 'child2 content'
    }
  },
  mounted () {
    console.log(this.$parent.parentVal) // "parent content"
  }
}
</script>

ref:如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子組件上,引用就指向組件實(shí)例$parent / $children:訪問父 / 子實(shí)例

需要注意的是:這兩種都是直接得到組件實(shí)例,使用后可以直接調(diào)用組件的方法或訪問數(shù)據(jù)。我們先來看個(gè)用 ref來訪問組件的例子:

component-a 子組件

export default {
  data () {
    return {
      title: 'Vue.js'
    }
  },
  methods: {
    sayHello () {
      window.alert('Hello');
    }
  }
}

父組件

<template>
  <component-a ref="comA"></component-a>
</template>
<script>
  export default {
    mounted () {
      const comA = this.$refs.comA;
      console.log(comA.title);  // Vue.js
      comA.sayHello();  // 彈窗
    }
  }
</script>

不過,這兩種方法的弊端是,無法在跨級(jí)或兄弟間通信。

parent.vue

<component-a></component-a>
<component-b></component-b>
<component-b></component-b>

我們想在 component-a 中,訪問到引用它的頁面中(這里就是 parent.vue)的兩個(gè) component-b 組件,那這種情況下,就得配置額外的插件或工具了,比如 Vuex 和 Bus 的解決方案。

多級(jí)組件嵌套需要傳遞數(shù)據(jù)時(shí),通常使用的方法是通過vuex。但如果僅僅是傳遞數(shù)據(jù),而不做中間處理,使用 vuex 處理,未免有點(diǎn)大材小用。為此Vue2.4 版本提供了另一種方法----$attrs/$listeners

$attrs:包含了父作用域中不被 prop 所識(shí)別 (且獲取) 的特性綁定 (class 和 style 除外)。當(dāng)一個(gè)組件沒有聲明任何 prop 時(shí),這里會(huì)包含所有父作用域的綁定 (class 和 style 除外),并且可以通過 v-bind="$attrs" 傳入內(nèi)部組件。通常配合 inheritAttrs 選項(xiàng)一起使用。

$listeners:包含了父作用域中的 (不含 .native 修飾器的) v-on 事件監(jiān)聽器。它可以通過 v-on="$listeners" 傳入內(nèi)部組件

$attrs

1) 包含了父作用域中不作為 prop 被識(shí)別 (且獲取) 的特性綁定 (class 和 style 除外) 2) 當(dāng)一個(gè)組件沒有聲明任何 prop 時(shí),這里會(huì)包含所有父作用域的綁定 (class 和 style 除外) 可以通過v-bind="$attrs" 將所有父作用域的綁定 (class、style、 ref 除外) 傳入內(nèi)部組件注: 在創(chuàng)建高級(jí)別的組件時(shí)非常有用

根組件HelloWorld.vue 中引入 ipc.vue

<ipc
   koa="ipcRef"
   name="go"
   id="id"
   ref="ref"
   style="border: 1px solid red;"
   class="className"
   >
</ipc>

ipc.vue  中引入 ipcChild.vue

<template>
  <div>
    <ipcChild v-bind="$attrs" selfDefine="selfDefine"></ipcChild>
  </div>
</template>

<script>
import ipcChild from './ipcChild'
export default {
  components: {
    ipcChild
  },
  mounted () {
    console.log(this.$attrs) // {id: "id", name: "go", koa: "ipcRef"}
  }
}
</script>

// ipcChild.vue中打印接收到的$attrs

<script>
export default {
  created () {
    console.log(this.$attrs) // "{"selfDefine":"selfDefine","koa":"ipcRef","name":"go","id":"id"}"
  }
}
</script>

$listeners

包含了父作用域中的 (不含 .native 修飾器的) v-on 事件監(jiān)聽器 通過 v-on="$listeners" 將父作用域的時(shí)間監(jiān)聽器傳入內(nèi)部組件

A、B、C三個(gè)組件依次嵌套, B嵌套在A中,C嵌套在B中。 借助 B 組件的中轉(zhuǎn),從上到下props依次傳遞,從下至上,$emit事件的傳遞,達(dá)到跨級(jí)組件通信的效果。$attrs以及$listeners 的出現(xiàn)解決的的問題,B 組件在其中傳遞props以及事件的過程中,不必在寫多余的代碼,僅僅是將 $attrs以及$listeners 向上或者向下傳遞即可。

跨級(jí)通信的案例

index.vue

<template>
  <div>
    <h3>浪里行舟</h3>
    <child-com1
      :foo="foo"
      :boo="boo"
      :coo="coo"
      :doo="doo"
      title="前端工匠"
    ></child-com1>
  </div>
</template>
<script>
const childCom1 = () => import("./childCom1.vue");
export default {
  components: { childCom1 },
  data() {
    return {
      foo: "Javascript",
      boo: "Html",
      coo: "CSS",
      doo: "Vue"
    };
  }
};
</script>

childCom1.vue

<template class="border">
  <div>
    <p>foo: {{ foo }}</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, // 可以關(guān)閉自動(dòng)掛載到組件根元素上的沒有在props聲明的屬性
  props: {
    foo: String // foo作為props屬性綁定
  },
  created() {
    console.log(this.$attrs); // { "boo": "Html", "coo": "CSS", "doo": "Vue", "title": "前端工匠" }
  }
};
</script>

childCom2.vue

<template>
  <div class="border">
    <p>boo: {{ boo }}</p>
    <p>childCom2: {{ $attrs }}</p>
    <child-com3 v-bind="$attrs"></child-com3>
  </div>
</template>
<script>
const childCom3 = () => import("./childCom3.vue");
export default {
  components: {
    childCom3
  },
  inheritAttrs: false,
  props: {
    boo: String
  },
  created() {
    console.log(this.$attrs); // { "coo": "CSS", "doo": "Vue", "title": "前端工匠" }
  }
};
</script>

childCom3.vue

<template>
  <div class="border">
    <p>childCom3: {{ $attrs }}</p>
  </div>
</template>
<script>
export default {
  props: {
    coo: String,
    title: String
  }
};
</script>

$attrs表示沒有繼承數(shù)據(jù)的對象,格式為{屬性名:屬性值}。Vue2.4提供了$attrs , $listeners 來傳遞數(shù)據(jù)與事件,跨級(jí)組件之間的通訊變得更簡單。

簡單來說:$attrs$listeners 是兩個(gè)對象,$attrs 里存放的是父組件中綁定的非 Props 屬性,$listeners里存放的是父組件中綁定的非原生事件。

Vue.observable

mixin

mixin (混入) (謹(jǐn)慎使用全局混入, 如有必要可以設(shè)計(jì)插件并引入使用)參見官方文檔

  • 一個(gè)混入對象可以包含任意組件選項(xiàng)。當(dāng)組件使用混入對象時(shí),所有混入對象的選項(xiàng)將被“混合”進(jìn)入該組件本身的選項(xiàng)

  • 當(dāng)組件和混入對象含有同名選項(xiàng)時(shí),這些選項(xiàng)將以恰當(dāng)?shù)姆绞竭M(jìn)行“合并”。數(shù)據(jù)對象在內(nèi)部會(huì)進(jìn)行遞歸合并,并在發(fā)生沖突時(shí)以組件數(shù)據(jù)優(yōu)先。

  • 同名鉤子函數(shù)將合并為一個(gè)數(shù)組,因此都將被調(diào)用。另外,混入對象的鉤子將在組件自身鉤子之前調(diào)用。

  • 值為對象的選項(xiàng),例如 methods、components 和 directives,將被合并為同一個(gè)對象。兩個(gè)對象鍵名沖突時(shí),取組件對象的鍵值對。

路由傳值 /引用數(shù)據(jù)類型值傳遞實(shí)現(xiàn)父子間數(shù)據(jù)的共享。

到此,關(guān)于“Vue組件的通信方式有哪些”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

vue
AI