當前位置:編程學習大全網 - 源碼下載 - 如何使用vuex實現兄弟組件通信

如何使用vuex實現兄弟組件通信

前言

vuex主要是是做數據交互,父子組件傳值可以很容易辦到,但是兄弟組件間傳值,需要先將值傳給父組件,再傳給子組件,異常麻煩。

下面這篇文章就來給大家介紹下vuex兄弟組件通信的方法,下面話不多說了,來壹起看看詳細的介紹吧

1. 核心想法

使用vuex進行兄弟組件通信的核心思路就是將vuex作為壹個store(vuex被設計的原因之壹),將每個子組件的數據都存放進去,每個子組件都從vuex裏獲取數據,其實就是壹句話——把vuex作為壹個橋

2. 具體代碼

父組件App.vue

<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>

<style>

#app {

font-family: 'Avenir', Helvetica, Arial, sans-serif;

-webkit-font-smoothing: antialiased;

-moz-osx-font-smoothing: grayscale;

text-align: center;

color: #2c3e50;

margin-top: 60px;

}

div {

margin: 10px;

}

</style>

子組件ChildA

<template>

<div id="childA">

<h1>我是A組件</h1>

<button @click="transform">點我讓B組件接收到數據</button>

<p>因為妳點了B,所以我的信息發生了變化:{{BMessage}}</p>

</div>

</template>

<script>

export default {

data() {

return {

AMessage: 'Hello,B組件,我是A組件'

}

},

computed: {

BMessage() {

// 這裏存儲從store裏獲取的B組件的數據

return this.$store.state.BMsg

}

},

methods: {

transform() {

// 觸發receiveAMsg,將A組件的數據存放到store裏去

this.$store.commit('receiveAMsg', {

AMsg: this.AMessage

})

}

}

}

</script>

<style>

div#childA {

border: 1px solid black;

}

</style>

子組件ChildB

<template>

<div id="childB">

<h1>我是B組件</h1>

<button @click="transform">點我讓A組件接收到數據</button>

<p>因為妳點了A,所以我的信息發生了變化:{{AMessage}}</p>

</div>

</template>

<script>

export default {

data() {

return {

BMessage: 'Hello,A組件,我是B組件'

}

},

computed: {

AMessage() {

// 這裏存儲從store裏獲取的A組件的數據

return this.$store.state.AMsg

}

},

methods: {

transform() {

// 觸發receiveBMsg,將B組件的數據存放到store裏去

this.$store.commit('receiveBMsg', {

BMsg: this.BMessage

})

}

}

}

</script>

<style>

div#childB {

border: 1px solid green;

}

</style>

vuex模塊store.js

import Vue from 'vue'

import Vuex from 'vuex'

Vue.use(Vuex)

const state = {

// 初始化A和B組件的數據,等待獲取

AMsg: '',

BMsg: ''

}

const mutations = {

receiveAMsg(state, payload) {

// 將A組件的數據存放於state

state.AMsg = payload.AMsg

},

receiveBMsg(state, payload) {

// 將B組件的數據存放於state

state.BMsg = payload.BMsg

}

}

export default new Vuex.Store({

state,

mutations

})

我把所有的代碼+註釋都放在github了,源碼鏈接,預覽鏈接

總結

  • 上一篇:assert的使用斷言
  • 下一篇:如何開啟小米路由器SSH root權限
  • copyright 2024編程學習大全網