Vue3 過10種組件通訊方式

本文簡(jiǎn)介

點(diǎn)贊 + 關(guān)注 + 收藏 = 學(xué)會(huì)了


本文講解 Vue 3.2 組件多種通訊方式的基礎(chǔ)用法,并且使用了 單文件組件 <script setup>

眾所周知,Vue.js 中一個(gè)很重要的知識(shí)點(diǎn)是組件通信,不管是業(yè)務(wù)類的開發(fā)還是組件庫開發(fā),都有各自的通訊方法。


本文適合:

  1. Vue 3 基礎(chǔ)的讀者。
  2. 打算開發(fā)組件庫的讀者。


本文會(huì)涉及的知識(shí)點(diǎn):

  1. Props
  2. emits
  3. expose / ref
  4. Non-Props
  5. v-model
  6. 插槽 slot
  7. provide / inject
  8. 總線 bus
  9. getCurrentInstance
  10. Vuex
  11. Pinia
  12. mitt.js


我會(huì)將上面羅列的知識(shí)點(diǎn)都寫一個(gè)簡(jiǎn)單的 demo。本文的目的是讓大家知道有這些方法可以用,所以并不會(huì)深挖每個(gè)知識(shí)點(diǎn)。

建議讀者跟著本文敲一遍代碼,然后根據(jù)本文給出的鏈接去深挖各個(gè)知識(shí)點(diǎn)。

收藏(學(xué)到)是自己的!



Props

父組件傳值給子組件(簡(jiǎn)稱:父?jìng)髯樱?/p>

Props 文檔


父組件

// Parent.vue

<template>
  <!-- 使用子組件 -->
  <Child :msg="message" />
</template>

<script setup>
import Child from './components/Child.vue' // 引入子組件

let message = '雷猴'
</script>

子組件

// Child.vue

<template>
  <div>
    {{ msg }}
  </div>
</template>

<script setup>

const props = defineProps({
  msg: {
    type: String,
    default: ''
  }
})

console.log(props.msg) // 在 js 里需要使用 props.xxx 的方式使用。在 html 中使用不需要 props

</script>


<script setup> 中必須使用 defineProps API 來聲明 props,它具備完整的推斷并且在 <script setup> 中是直接可用的。

更多細(xì)節(jié)請(qǐng)看 文檔


<script setup> 中,defineProps 不需要另外引入。


props 其實(shí)還能做很多事情,比如:設(shè)置默認(rèn)值 default ,類型驗(yàn)證 type ,要求必傳 required ,自定義驗(yàn)證函數(shù) validator 等等。

大家可以去官網(wǎng)看看,這是必須掌握的知識(shí)點(diǎn)!

props 文檔



emits

子組件通知父組件觸發(fā)一個(gè)事件,并且可以傳值給父組件。(簡(jiǎn)稱:子傳父)

emits 文檔


01.gif

父組件

// Parent.vue

<template>
  <div>父組件:{{ message }}</div>
  <!-- 自定義 changeMsg 事件 -->
  <Child @changeMsg="changeMessage" />
</template>

<script setup>
import { ref } from 'vue'
import Child from './components/Child.vue'

let message = ref('雷猴')

// 更改 message 的值,data是從子組件傳過來的
function changeMessage(data) {
  message.value = data
}
</script>

子組件

// Child.vue

<template>
  <div>
    子組件:<button @click="handleClick">子組件的按鈕</button>
  </div>
</template>

<script setup>

// 注冊(cè)一個(gè)自定義事件名,向上傳遞時(shí)告訴父組件要觸發(fā)的事件。
const emit = defineEmits(['changeMsg'])

function handleClick() {
  // 參數(shù)1:事件名
  // 參數(shù)2:傳給父組件的值
  emit('changeMsg', '鯊魚辣椒')
}

</script>

props 一樣,在 <script setup> 中必須使用 defineEmits API 來聲明 emits,它具備完整的推斷并且在 <script setup> 中是直接可用的。更多細(xì)節(jié)請(qǐng)看 文檔

<script setup> 中,defineEmits 不需要另外引入。



expose / ref

子組件可以通過 expose 暴露自身的方法和數(shù)據(jù)。

父組件通過 ref 獲取到子組件并調(diào)用其方法或訪問數(shù)據(jù)。

expose 文檔


用例子說話

02.gif

父組件

// Parent.vue

<template>
  <div>父組件:拿到子組件的message數(shù)據(jù):{{ msg }}</div>
  <button @click="callChildFn">調(diào)用子組件的方法</button>

  <hr>

  <Child ref="com" />
</template>

<script setup>
import { ref, onMounted } from 'vue'
import Child from './components/Child.vue'

const com = ref(null) // 通過 模板ref 綁定子組件

const msg = ref('')

onMounted(() => {
  // 在加載完成后,將子組件的 message 賦值給 msg
  msg.value = com.value.message
})

function callChildFn() {
  // 調(diào)用子組件的 changeMessage 方法
  com.value.changeMessage('蒜頭王八')

  // 重新將 子組件的message 賦值給 msg
  msg.value = com.value.message
}
</script>

子組件

// Child.vue

<template>
  <div>子組件:{{ message }}</div>
</template>

<script setup>
import { ref } from 'vue'

const message = ref('蟑螂惡霸')

function changeMessage(data) {
  message.value = data
}

使用 defineExpose 向外暴露指定的數(shù)據(jù)和方法
defineExpose({
  message,
  changeMessage
})

</script>

<script setup> 中,defineExpose 不需要另外引入。

expose 文檔

defineExpose 文檔



Non-Props

所謂的 Non-Props 就是 非 Prop 的 Attribute

意思是在子組件中,沒使用 propemits 定義的 attribute,可以通過 $attrs 來訪問。

常見的有 classstyleid

非 Prop 的 Attribute 文檔


還是舉個(gè)例子會(huì)直觀點(diǎn)


單個(gè)根元素的情況

父組件

// Parent.vue

<template>
  <Child msg="雷猴 世界!" name="鯊魚辣椒" />
</template>

<script setup>
import { ref } from 'vue'
import Child from './components/Child.vue'
</script>

子組件

// Child.vue

<template>
  <div>子組件:打開控制臺(tái)看看</div>
</template>
03.png

打開控制臺(tái)可以看到,屬性被掛到 HTML 元素上了。


多個(gè)元素的情況

但在 Vue3 中,組件已經(jīng)沒規(guī)定只能有一個(gè)根元素了。如果子組件是多個(gè)元素時(shí),上面的例子就不生效了。

// Child.vue

<template>
  <div>子組件:打開控制臺(tái)看看</div>
  <div>子組件:打開控制臺(tái)看看</div>
</template>
04.png


此時(shí)可以使用 $attrs 的方式進(jìn)行綁定。

// Child.vue

<template>
  <div :message="$attrs.msg">只綁定指定值</div>
  <div v-bind="$attrs">全綁定</div>
</template>
05.png



v-model

v-modelVue 的一個(gè)語法糖。在 Vue3 中的玩法就更多(暈)了。

單值的情況

組件上的 v-model 使用 modelValue 作為 prop 和 update:modelValue 作為事件。

v-model 參數(shù)文檔

父組件

// Parent.vue

<template>
  <Child v-model="message" />
</template>

<script setup>
import { ref } from 'vue'
import Child from './components/Child.vue'

const message = ref('雷猴')
</script>

子組件

// Child.vue

<template>
  <div @click="handleClick">{{modelValue}}</div>
</template>

<script setup>
import { ref } from 'vue'

// 接收
const props = defineProps([
  'modelValue' // 接收父組件使用 v-model 傳進(jìn)來的值,必須用 modelValue 這個(gè)名字來接收
])

const emit = defineEmits(['update:modelValue']) // 必須用 update:modelValue 這個(gè)名字來通知父組件修改值

function handleClick() {
  // 參數(shù)1:通知父組件修改值的方法名
  // 參數(shù)2:要修改的值
  emit('update:modelValue', '噴射河馬')
}

</script>
06.gif


你也可以這樣寫,更加簡(jiǎn)單

子組件

// Child.vue

<template>
  <div @click="$emit('update:modelValue', '噴射河馬')">{{modelValue}}</div>
</template>

<script setup>
import { ref } from 'vue'

// 接收
const props = defineProps([
  'modelValue' // 接收父組件使用 v-model 傳進(jìn)來的值,必須用 modelValue 這個(gè)名字來接收
])

</script>


多個(gè) v-model 綁定

多個(gè) v-model 綁定 文檔

父組件

// Parent.vue

<template>
  <Child v-model:msg1="message1" v-model:msg2="message2" />
</template>

<script setup>
import { ref } from 'vue'
import Child from './components/Child.vue'

const message1 = ref('雷猴')

const message2 = ref('蟑螂惡霸')
</script>

子組件

// Child.vue

<template>
  <div><button @click="changeMsg1">修改msg1</button> {{msg1}}</div>

  <div><button @click="changeMsg2">修改msg2</button> {{msg2}}</div>
</template>

<script setup>
import { ref } from 'vue'

// 接收
const props = defineProps({
  msg1: String,
  msg2: String
})

const emit = defineEmits(['update:msg1', 'update:msg2'])

function changeMsg1() {
  emit('update:msg1', '鯊魚辣椒')
}

function changeMsg2() {
  emit('update:msg2', '蝎子萊萊')
}

</script>
07.gif


v-model 修飾符

v-model 還能通過 . 的方式傳入修飾。

v-model 修飾符 文檔

父組件

// Parent.vue

<template>
  <Child v-model.uppercase="message" />
</template>

<script setup>
import { ref } from 'vue'
import Child from './components/Child.vue'

const message = ref('hello')
</script>

子組件

// Child.vue

<template>
  <div>{{modelValue}}</div>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const props = defineProps([
  'modelValue',
  'modelModifiers'
])

const emit = defineEmits(['update:modelValue'])

onMounted(() => {
  // 判斷有沒有 uppercase 修飾符,有的話就執(zhí)行 toUpperCase() 方法
  if (props.modelModifiers.uppercase) {
    emit('update:modelValue', props.modelValue.toUpperCase())
  }
})

</script>
08.png



插槽 slot

插槽可以理解為傳一段 HTML 片段給子組件。子組件將 <slot> 元素作為承載分發(fā)內(nèi)容的出口。

插槽 文檔

本文打算講講日常用得比較多的3種插槽:默認(rèn)插槽、具名插槽、作用域插槽。


默認(rèn)插槽

插槽的基礎(chǔ)用法非常簡(jiǎn)單,只需在 子組件 中使用 <slot> 標(biāo)簽,就會(huì)將父組件傳進(jìn)來的 HTML 內(nèi)容渲染出來。

默認(rèn)插槽 文檔

父組件

// Parent.vue

<template>
  <Child>
    <div>雷猴啊</div>
  </Child>
</template>

子組件

// Child.vue

<template>
  <div>
    <slot></slot>
  </div>
</template>


具名插槽

具名插槽 就是在 默認(rèn)插槽 的基礎(chǔ)上進(jìn)行分類,可以理解為對(duì)號(hào)入座。

具名插槽 文檔

09.png

父組件

// Parent.vue

<template>
  <Child>
    <template v-slot:monkey>
      <div>雷猴啊</div>
    </template>

    <button>鯊魚辣椒</button>
  </Child>
</template>

子組件

// Child.vue

<template>
  <div>
    <!-- 默認(rèn)插槽 -->
    <slot></slot>
    <!-- 具名插槽 -->
    <slot name="monkey"></slot>
  </div>
</template>


父組件需要使用 <template> 標(biāo)簽,并在標(biāo)簽上使用 v-solt: + 名稱

子組件需要在 <slot> 標(biāo)簽里用 name= 名稱 對(duì)應(yīng)接收。

這就是 對(duì)號(hào)入座


最后需要注意的是,插槽內(nèi)容的排版順序,是 以子組件里的排版為準(zhǔn)

上面這個(gè)例子就是這樣,你可以仔細(xì)觀察子組件傳入順序和子組件的排版順序。


作用域插槽

如果你用過 Element-Plus 這類 UI框架 的 Table ,應(yīng)該就能很好的理解什么叫作用域插槽。

作用域插槽 文檔


10.png

父組件

// Parent.vue

<template>
  <!-- v-slot="{scope}" 獲取子組件傳上來的數(shù)據(jù) -->
  <!-- :list="list" 把list傳給子組件 -->
  <Child v-slot="{scope}" :list="list">
    <div>
      <div>名字:{{ scope.name }}</div>
      <div>職業(yè):{{ scope.occupation }}</div>
      <hr>
    </div>
  </Child>
</template>

<script setup>
import { ref } from 'vue'
import Child from './components/Child.vue'

const list = ref([
  { name: '雷猴', occupation: '打雷'},
  { name: '鯊魚辣椒', occupation: '游泳'},
  { name: '蟑螂惡霸', occupation: '掃地'},
])
</script>

子組件

// Child.vue

<template>
  <div>
    <!-- 用 :scope="item" 返回每一項(xiàng) -->
    <slot v-for="item in list" :scope="item" />
  </div>
</template>

<script setup>
const props = defineProps({
  list: {
    type: Array,
    default: () => []
  }
})
</script>

我沒寫樣式,所以用 hr 元素讓視覺上看上去比較清晰 我就是懶



provide / inject

遇到多層傳值時(shí),使用 propsemit 的方式會(huì)顯得比較笨拙。這時(shí)就可以用 provideinject 了。

provide 是在父組件里使用的,可以往下傳值。

inject 是在子(后代)組件里使用的,可以網(wǎng)上取值。

無論組件層次結(jié)構(gòu)有多深,父組件都可以作為其所有子組件的依賴提供者。

provide / inject 文檔

11.png


父組件

// Parent.vue

<template>
  <Child></Child>
</template>

<script setup>
import { ref, provide, readonly } from 'vue'
import Child from './components/Child.vue'

const name = ref('猛虎下山')
const msg = ref('雷猴')

// 使用readonly可以讓子組件無法直接修改,需要調(diào)用provide往下傳的方法來修改
provide('name', readonly(name))

provide('msg', msg)

provide('changeName', (value) => {
  name.value = value
})
</script>

子組件

// Child.vue

<template>
  <div>
    <div>msg: {{ msg }}</div>
    <div>name: {{name}}</div>
    <button @click="handleClick">修改</button>
  </div>
</template>

<script setup>
import { inject } from 'vue'

const name = inject('name', 'hello') // 看看有沒有值,沒值的話就適用默認(rèn)值(這里默認(rèn)值是hello)
const msg = inject('msg')
const changeName = inject('changeName')

function handleClick() {
  // 這樣寫不合適,因?yàn)関ue里推薦使用單向數(shù)據(jù)流,當(dāng)父級(jí)使用readonly后,這行代碼是不會(huì)生效的。沒使用之前才會(huì)生效。
  // name.value = '雷猴'

  // 正確的方式
  changeName('虎軀一震')

  // 因?yàn)?msg 沒被 readonly 過,所以可以直接修改值
  msg.value = '世界'
}
</script>

provide 可以配合 readonly 一起使用,詳情可以看上面例子和注釋。

provideinject 其實(shí)主要是用在深層關(guān)系中傳值,上面的例子只有父子2層,只是為了舉例說明 我懶



總線 bus

Vue2 有總線傳值的方法,我們?cè)?Vue3 中也可以自己模擬。

這個(gè)方式其實(shí)有點(diǎn)像 Vuex 或者 Pinia 那樣,弄一個(gè)獨(dú)立的工具出來專門控制數(shù)據(jù)。

但和 VuexPinia 相比,我們自己寫的這個(gè)方法并沒有很好的數(shù)據(jù)跟蹤之類的特性。


原理

我們創(chuàng)建一個(gè) Bus.js 文件,用來控制數(shù)據(jù)和注冊(cè)事件的。

Bus.js 里有一個(gè) Bus

  • eventList 是必須項(xiàng),用來存放事件列表的。
  • constructor 里除了 eventList 外,其他都是自定義數(shù)據(jù),公共數(shù)據(jù)就是存在這里的。
  • $on 方法用來注冊(cè)事件。
  • $emit 方法可以調(diào)用 $on 里的事件。
  • $off 方法可以注銷 eventList 里的事件。


然后需要用到總線的組件,都導(dǎo)入 Bus.js ,就可以共同操作一份數(shù)據(jù)了。


Bus.js

import { ref } from 'vue'

class Bus {
  constructor() {
    // 收集訂閱信息,調(diào)度中心
    this.eventList = {}, // 事件列表,這項(xiàng)是必須的
    // 下面的都是自定義值
    this.msg = ref('這是一條總線的信息')
  }

  // 訂閱
  $on(name, fn) {
    this.eventList[name] = this.eventList[name] || []
    this.eventList[name].push(fn)
  }

  // 發(fā)布
  $emit(name, data) {
    if (this.eventList[name]) {
      this.eventList[name].forEach((fn) => {
        fn(data)
      });
    }
  }

  // 取消訂閱
  $off(name) {
      if (this.eventList[name]) {
      delete this.eventList[name]
    }
  }
}

export default new Bus()

父組件

// Parent.vue

<template>
  <div>
    父組件: 
    <span style="margin-right: 30px;">message: {{ message }}</span>
    <span>msg: {{ msg }}</span>
  </div>
  <Child></Child>
</template>

<script setup>
import { ref } from 'vue'
import Bus from './Bus.js'
import Child from './components/Child.vue'

const msg = ref(Bus.msg)

const message = ref('hello')

// 用監(jiān)聽的寫法
Bus.$on('changeMsg', data => {
  message.value = data
})

</script>

子組件

// Child.vue

<template>
  <div>
    子組件:
    <button @click="handleBusEmit">觸發(fā)Bus.$emit</button>
    <button @click="changeBusMsg">修改總線里的 msg</button>
  </div>
</template>

<script setup>
import Bus from '../Bus.js'

function handleBusEmit() {
  Bus.$emit('changeMsg', '雷猴啊')
}

function changeBusMsg() {
  // console.log(Bus.msg)
  Bus.msg.value = '在子組件里修改了總線的值'
}
</script>

這個(gè)方法其實(shí)還挺好用的,但光看可能有點(diǎn)懵,請(qǐng)大家務(wù)必親手敲一下代碼實(shí)踐一下。



getCurrentInstance

getcurrentinstancevue 提供的一個(gè)方法,支持訪問內(nèi)部組件實(shí)例。

getCurrentInstance 只暴露給高階使用場(chǎng)景,典型的比如在庫中。強(qiáng)烈反對(duì)在應(yīng)用的代碼中使用 getCurrentInstance。請(qǐng)不要把它當(dāng)作在組合式 API 中獲取 this 的替代方案來使用。

說白了,這個(gè)方法 適合在開發(fā)組件庫的情況下使用,不適合日常業(yè)務(wù)開發(fā)中使用。

getCurrentInstance 只能setup生命周期鉤子中調(diào)用。

getcurrentinstance 文檔


<script setup> 中,我模擬了類似 $parent$children 的方式。

父組件

// Parent.vue

<template>
  <div>父組件 message 的值: {{ message }}</div>
  <button @click="handleClick">獲取子組件</button>
  <Child></Child>
  <Child></Child>
</template>

<script setup>
import { ref, getCurrentInstance, onMounted } from 'vue'
import Child from './components/Child.vue'

const message = ref('雷猴啊')

let instance = null

onMounted(() => {
  instance = getCurrentInstance()
})

// 子組件列表
let childrenList = []

// 注冊(cè)組件
function registrationCom(com) {
  childrenList.push(com)
}

function handleClick() {
  if (childrenList.length > 0) {
    childrenList.forEach(item => {
      console.log('組件實(shí)例:', item)
      console.log('組件名(name):', item.type.name)
      console.log('組件輸入框的值:', item.devtoolsRawSetupState.inputValue)
      console.log('---------------------------------------')
    })
  }
}

</script>

子組件

// Child.vue

<template>
  <div>
    <div>----------------------------</div>
    子組件:<button @click="handleClick">獲取父組件的值</button>
    <br>
    <input type="text" v-model="inputValue">
  </div>
</template>

<script>
export default {
  name: 'ccccc'
}
</script>

<script setup>
import { getCurrentInstance, onMounted, nextTick, ref } from 'vue'

const inputValue = ref('')

let instance = null

onMounted(() => {
  instance = getCurrentInstance()
  nextTick(() => {
    instance.parent.devtoolsRawSetupState.registrationCom(instance)
  })

})

function handleClick() {
  let msg = instance.parent.devtoolsRawSetupState.message
  msg.value = '哈哈哈哈哈哈'
}

</script>

可以將代碼復(fù)制到你的項(xiàng)目中運(yùn)行試試看,最好還是敲一遍咯。



Vuex

Vuex 主要解決 跨組件通信 的問題。

Vue3 中,需要使用 Vuex v4.x 版本。


安裝

npm 或者 Yarn 安裝到項(xiàng)目中。

npm install vuex@next --save

# 或

yarn add vuex@next --save


使用

安裝成功后,在 src 目錄下創(chuàng)建 store 目錄,再在 store 下創(chuàng)建 index.js 文件。

// store/index.js

import { createStore } from 'vuex'

export default createStore({
  state: {
  },
  getters: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  }
})

store/index.js 下輸入以上內(nèi)容。

  • state:數(shù)據(jù)倉庫,用來存數(shù)據(jù)的。
  • getters:獲取數(shù)據(jù)的,有點(diǎn)像 computed 的用法(個(gè)人覺得)。
  • mutations: 更改 state 數(shù)據(jù)的方法都要寫在 mutations 里。
  • actions:異步異步異步,異步的方法都寫在這里,但最后還是需要通過 mutations 來修改 state 的數(shù)據(jù)。
  • modules:分包。如果項(xiàng)目比較大,可以將業(yè)務(wù)拆散成獨(dú)立模塊,然后分文件管理和存放。


然后在 src/main.js 中引入

import { createApp } from 'vue'
import App from './App.vue'
import store from './store'

const app = createApp(App)

app
  .use(store)
  .mount('#app')


State

store/index.js

// store/index.js

import { createStore } from 'vuex'

export default createStore({
  state: {
    msg: '雷猴'
  }
})

組件

// xxx.vue

<script setup>
import { useStore } from 'vuex'

const store = useStore()

console.log(store.state.msg) // 雷猴
</script>


Getter

我覺得 Getter 方法和 computed 是有點(diǎn)像的。

比如我們需要過濾一下數(shù)據(jù),或者返回時(shí)組裝一下數(shù)據(jù),都可以用 Getter 方法。

store/index.js

// store/index.js

import { createStore } from 'vuex'

export default createStore({
  state: {
    msg: '雷猴'
  },
  getters: {
    getMsg(state) {
      return state.msg + ' 世界!'
    }
  }
})

組件

// xxx.vue

<script setup>
import { useStore } from 'vuex'

const store = useStore()

console.log(store.getters.getMsg) // 雷猴 世界!
</script>


Mutation

Mutation 是修改 State 數(shù)據(jù)的唯一方法,這樣 Vuex 才可以跟蹤數(shù)據(jù)流向。

在組件中通過 commit 調(diào)用即可。


store/index.js

// store/index.js

import { createStore } from 'vuex'

export default createStore({
  state: {
    msg: '雷猴'
  },
  mutations: {
    changeMsg(state, data) {
      state.msg = data
    }
  }
})

組件

// xxx.vue

<script setup>
import { useStore } from 'vuex'

const store = useStore()

store.commit('changeMsg', '蒜頭王八')

console.log(store.state.msg) // 蒜頭王八
</script>


Action

我習(xí)慣將異步的東西放在 Action 方法里寫,然后在組件使用 dispatch 方法調(diào)用。


store/index.js

// store/index.js

import { createStore } from 'vuex'

export default createStore({
  state: {
    msg: '雷猴'
  },
  mutations: {
    changeMsg(state, data) {
      state.msg = data
    }
  },
  actions: {
    fetchMsg(context) {
      // 模擬ajax請(qǐng)求
      setTimeout(() => {
        context.commit('changeMsg', '鯊魚辣椒')
      }, 1000)
    }
  }
})

組件

// xxx.vue

<script setup>
import { useStore } from 'vuex'

const store = useStore()

store.dispatch('fetchMsg')
</script>


Module

Module 就是傳說中的分包了。這需要你將不同模塊的數(shù)據(jù)拆分成一個(gè)個(gè) js 文件。

我舉個(gè)例子,目錄如下

store
|- index.js
|- modules/
  |- user.js
  |- goods.js
  • index.js 對(duì)外的出口(主文件)
  • modules/user.js 用戶相關(guān)模塊
  • modules/goods.js 商品模塊


index.js

import { createStore } from 'vuex'
import user from './modules/user'
import goods from './modules/goods'

export default createStore({
  state: {},
  getters: {},
  mutations: {},
  actions: {},
  modules: {
    user,
    goods
  }
})

user.js

const user = {
  state: {
  },
  getters: {
  },
  mutations: {
  },
  actions: {
  }
}

export default user

goods.js

const goods = {
  state: {
  },
  getters: {
  },
  mutations: {
  },
  actions: {
  }
}

export default goods


然后在各個(gè)模塊里放入相應(yīng)的數(shù)據(jù)和方法就行。

在組建中調(diào)用方法和訪問數(shù)據(jù),都和之前的用法差不多的。


以上就是 Vuex 的基礎(chǔ)用法。除此之外,Vuex 還有各種語法糖,大家可以自行查閱 官方文檔



Pinia

Pinia 是最近比較火熱的一個(gè)工具,也是用來處理 跨組件通信 的,極大可能成為 Vuex 5

Pinia 文檔


從我使用 Pinia 一陣后的角度來看,PiniaVuex 相比有以下優(yōu)點(diǎn):

  • 調(diào)用時(shí)代碼跟簡(jiǎn)潔了。
  • 對(duì) TS 更友好。
  • 合并了 VuexMutationAction 。天然的支持異步了。
  • 天然分包。

除此之外,Pinia 官網(wǎng)還說它適用于 Vue2Vue3。但我沒試過在 Vue2 中使用 我懶得試


Pinia 簡(jiǎn)化了狀態(tài)管理模塊,只用這3個(gè)東西就能應(yīng)對(duì)日常大多任務(wù)。

  • state:存儲(chǔ)數(shù)據(jù)的倉庫
  • getters:獲取和過濾數(shù)據(jù)(跟 computed 有點(diǎn)像)
  • actions:存放 “修改 state ”的方法


我舉個(gè)簡(jiǎn)單的例子


安裝

npm install pinia

# 或

yarn add pinia


注冊(cè)

src 目錄下創(chuàng)建 store 目錄,再在 store 里創(chuàng)建 index.jsuser.js

目錄結(jié)構(gòu)如下

store
|- index.js
|- user.js

index.js

import { createPinia } from 'pinia'

const store = createPinia()

export default store

user.js

常見的寫法有2種,選其中一種就行。

import { defineStore } from 'pinia'

// 寫法1
export const useUserStore = defineStore({
  id: 'user', // id必填,且需要唯一
  state: () => {
    return {
      name: '雷猴'
    }
  },
  getters: {
    fullName: (state) => {
      return '我叫 ' + state.name
    }
  },
  actions: {
    updateName(name) {
      this.name = name
    }
  }
})


// 寫法2
export const useUserStore = defineStore('user',{
  state: () => {
    return {
      name: '雷猴'
    }
  },
  getters: {
    fullName: (state) => {
      return '我叫 ' + state.name
    }
  },
  actions: {
    updateName(name) {
      this.name = name
    }
  }
})


然后在 src/main.js 中引入 store/index.js

src/main.js

import { createApp } from 'vue'
import App from './App.vue'
import store from './store'

const app = createApp(App)

app
  .use(store)
  .mount('#app')


在組件中使用

組件

// xxx.vue

<template>
  <div>
    <div>name: {{ name }}</div>
    <div>全名:{{ fullName }}</div>
    <button @click="handleClick">修改</button>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()

// const name = computed(() => userStore.name)

// 建議
const { name, fullName } = storeToRefs(userStore)


function handleClick() {
  // 不建議這樣改
  // name.value = '蝎子萊萊'

  // 推薦的寫法!!!
  userStore.updateName('李四')
}
</script>


啰嗦兩句

其實(shí) Pinia 的用法和 Vuex 是挺像的,默認(rèn)就是分包的邏輯,在這方面我支持 菠蘿(Pinia)

Pinia 還提供了多種語法糖,強(qiáng)烈建議閱讀一下 官方文檔



mitt.js

我們前面用到的 總線 Bus 方法,其實(shí)和 mitt.js 有點(diǎn)像,但 mitt.js 提供了更多的方法。

比如:

  • on:添加事件
  • emit:執(zhí)行事件
  • off:移除事件
  • clear:清除所有事件


mitt.js 不是專門給 Vue 服務(wù)的,但 Vue 可以利用 mitt.js 做跨組件通信。


github 地址

npm 地址


安裝

npm i mitt 


使用

我模擬一下 總線Bus 的方式。

我在同級(jí)目錄創(chuàng)建3個(gè)文件用作模擬。

Parent.vue
Child.vue
Bus.js


Bus.js

// Bus.js

import mitt from 'mitt'
export default mitt()

Parent.vue

// Parent.vue

<template>
  <div>
    Mitt
    <Child />
  </div>
</template>

<script setup>
import Child from './Child.vue'
import Bus from './Bus.js'

Bus.on('sayHello', () => console.log('雷猴啊'))
</script>

Child.vue

// Child.vue

<template>
  <div>
    Child:<button @click="handleClick">打聲招呼</button>
  </div>
</template>

<script setup>
import Bus from './Bus.js'

function handleClick() {
  Bus.emit('sayHello')
}
</script>


此時(shí),點(diǎn)擊 Child.vue 上的按鈕,在控制臺(tái)就會(huì)執(zhí)行在 Parent.vue 里定義的方法。


mitt.js 的用法其實(shí)很簡(jiǎn)單,建議跟著 官方示例 敲一下代碼,幾分鐘就上手了。



推薦閱讀

??《console.log也能插圖》

??《Vite 搭建 Vue2 項(xiàng)目(Vue2 + vue-router + vuex)》


如果本文對(duì)你有幫助,也希望你可以 點(diǎn)贊 關(guān)注 收藏 ~ 這對(duì)我很有用 ~

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,967評(píng)論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,273評(píng)論 3 415
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,870評(píng)論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,742評(píng)論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,527評(píng)論 6 407
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,010評(píng)論 1 322
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,108評(píng)論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,250評(píng)論 0 288
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,769評(píng)論 1 333
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,656評(píng)論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,853評(píng)論 1 369
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,371評(píng)論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,103評(píng)論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,472評(píng)論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,717評(píng)論 1 281
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,487評(píng)論 3 390
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,815評(píng)論 2 372

推薦閱讀更多精彩內(nèi)容