Vue3中10多種組件通訊方法小結(jié)
本文講解 Vue 3.2 組件多種通訊方式的基礎(chǔ)用法,并且使用了 單文件組件 <script setup> 。
眾所周知,Vue.js 中一個很重要的知識點是組件通信,不管是業(yè)務(wù)類的開發(fā)還是組件庫開發(fā),都有各自的通訊方法。
本文適合:
- 有
Vue 3基礎(chǔ)的讀者。 - 打算開發(fā)組件庫的讀者。
本文會涉及的知識點:
- Props
- emits
- expose / ref
- Non-Props
- v-model
- 插槽 slot
- provide / inject
- 總線 bus
- getCurrentInstance
- Vuex
- Pinia
- mitt.js
我會將上面羅列的知識點都寫一個簡單的 demo。本文的目的是讓大家知道有這些方法可以用,所以并不會深挖每個知識點。
建議讀者跟著本文敲一遍代碼,然后根據(jù)本文給出的鏈接去深挖各個知識點。
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é)請看 文檔。
在 <script setup> 中,defineProps 不需要另外引入。
props 其實還能做很多事情,比如:設(shè)置默認(rèn)值 default ,類型驗證 type ,要求必傳 required ,自定義驗證函數(shù) validator 等等。
大家可以去官網(wǎng)看看,這是必須掌握的知識點!
emits
子組件通知父組件觸發(fā)一個事件,并且可以傳值給父組件。(簡稱:子傳父)

父組件
// 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>
// 注冊一個自定義事件名,向上傳遞時告訴父組件要觸發(fā)的事件。
const emit = defineEmits(['changeMsg'])
function handleClick() {
// 參數(shù)1:事件名
// 參數(shù)2:傳給父組件的值
emit('changeMsg', '鯊魚辣椒')
}
</script>和 props 一樣,在 <script setup> 中必須使用 defineEmits API 來聲明 emits,它具備完整的推斷并且在 <script setup> 中是直接可用的。更多細(xì)節(jié)請看 文檔。
在 <script setup> 中,defineEmits 不需要另外引入。
expose / ref
子組件可以通過 expose 暴露自身的方法和數(shù)據(jù)。
父組件通過 ref 獲取到子組件并調(diào)用其方法或訪問數(shù)據(jù)。
用例子說話

父組件
// 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 不需要另外引入。
Non-Props
所謂的 Non-Props 就是 非 Prop 的 Attribute。
意思是在子組件中,沒使用 prop 或 emits 定義的 attribute,可以通過 $attrs 來訪問。
常見的有 class 、style 和 id。
還是舉個例子會直觀點
單個根元素的情況
父組件
// Parent.vue
<template>
<Child msg="雷猴 世界!" name="鯊魚辣椒" />
</template>
<script setup>
import { ref } from 'vue'
import Child from './components/Child.vue'
</script>子組件
// Child.vue <template> <div>子組件:打開控制臺看看</div> </template>

打開控制臺可以看到,屬性被掛到 HTML 元素上了。
多個元素的情況
但在 Vue3 中,組件已經(jīng)沒規(guī)定只能有一個根元素了。如果子組件是多個元素時,上面的例子就不生效了。
// Child.vue <template> <div>子組件:打開控制臺看看</div> <div>子組件:打開控制臺看看</div> </template>

此時可以使用 $attrs 的方式進行綁定。
// Child.vue <template> <div :message="$attrs.msg">只綁定指定值</div> <div v-bind="$attrs">全綁定</div> </template>

v-model
v-model 是 Vue 的一個語法糖。在 Vue3 中的玩法就更多(暈)了。
單值的情況
組件上的 v-model 使用 modelValue 作為 prop 和 update:modelValue 作為事件。
父組件
// 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 傳進來的值,必須用 modelValue 這個名字來接收
])
const emit = defineEmits(['update:modelValue']) // 必須用 update:modelValue 這個名字來通知父組件修改值
function handleClick() {
// 參數(shù)1:通知父組件修改值的方法名
// 參數(shù)2:要修改的值
emit('update:modelValue', '噴射河馬')
}
</script>

你也可以這樣寫,更加簡單
子組件
// Child.vue
<template>
<div @click="$emit('update:modelValue', '噴射河馬')">{{modelValue}}</div>
</template>
<script setup>
import { ref } from 'vue'
// 接收
const props = defineProps([
'modelValue' // 接收父組件使用 v-model 傳進來的值,必須用 modelValue 這個名字來接收
])
</script>
多個 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>

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>

插槽 slot
插槽可以理解為傳一段 HTML 片段給子組件。子組件將 <slot> 元素作為承載分發(fā)內(nèi)容的出口。
本文打算講講日常用得比較多的3種插槽:默認(rèn)插槽、具名插槽、作用域插槽。
默認(rèn)插槽
插槽的基礎(chǔ)用法非常簡單,只需在 子組件 中使用 <slot> 標(biāo)簽,就會將父組件傳進來的 HTML 內(nèi)容渲染出來。
父組件
// Parent.vue
<template>
<Child>
<div>雷猴啊</div>
</Child>
</template>
子組件
// Child.vue
<template>
<div>
<slot></slot>
</div>
</template>
具名插槽
具名插槽 就是在 默認(rèn)插槽 的基礎(chǔ)上進行分類,可以理解為對號入座。

父組件
// 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= 名稱 對應(yīng)接收。
這就是 對號入座。
最后需要注意的是,插槽內(nèi)容的排版順序,是 以子組件里的排版為準(zhǔn)。
上面這個例子就是這樣,你可以仔細(xì)觀察子組件傳入順序和子組件的排版順序。
作用域插槽
如果你用過 Element-Plus 這類 UI框架 的 Table ,應(yīng)該就能很好的理解什么叫作用域插槽。

父組件
// 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" 返回每一項 -->
<slot v-for="item in list" :scope="item" />
</div>
</template>
<script setup>
const props = defineProps({
list: {
type: Array,
default: () => []
}
})
</script>
我沒寫樣式,所以用 hr 元素讓視覺上看上去比較清晰 我就是懶。
provide / inject
遇到多層傳值時,使用 props 和 emit 的方式會顯得比較笨拙。這時就可以用 provide 和 inject 了。
provide 是在父組件里使用的,可以往下傳值。
inject 是在子(后代)組件里使用的,可以網(wǎng)上取值。
無論組件層次結(jié)構(gòu)有多深,父組件都可以作為其所有子組件的依賴提供者。

父組件
// 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() {
// 這樣寫不合適,因為vue里推薦使用單向數(shù)據(jù)流,當(dāng)父級使用readonly后,這行代碼是不會生效的。沒使用之前才會生效。
// name.value = '雷猴'
// 正確的方式
changeName('虎軀一震')
// 因為 msg 沒被 readonly 過,所以可以直接修改值
msg.value = '世界'
}
</script>
provide 可以配合 readonly 一起使用,詳情可以看上面例子和注釋。
provide 和 inject 其實主要是用在深層關(guān)系中傳值,上面的例子只有父子2層,只是為了舉例說明 我懶。
總線 bus
在 Vue2 有總線傳值的方法,我們在 Vue3 中也可以自己模擬。
這個方式其實有點像 Vuex 或者 Pinia 那樣,弄一個獨立的工具出來專門控制數(shù)據(jù)。
但和 Vuex 或 Pinia 相比,我們自己寫的這個方法并沒有很好的數(shù)據(jù)跟蹤之類的特性。
原理
我們創(chuàng)建一個 Bus.js 文件,用來控制數(shù)據(jù)和注冊事件的。
Bus.js 里有一個 Bus 類
eventList是必須項,用來存放事件列表的。constructor里除了eventList外,其他都是自定義數(shù)據(jù),公共數(shù)據(jù)就是存在這里的。$on方法用來注冊事件。$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 = {}, // 事件列表,這項是必須的
// 下面的都是自定義值
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>
這個方法其實還挺好用的,但光看可能有點懵,請大家務(wù)必親手敲一下代碼實踐一下。
getCurrentInstance
getcurrentinstance 是 vue 提供的一個方法,支持訪問內(nèi)部組件實例。
getCurrentInstance只暴露給高階使用場景,典型的比如在庫中。強烈反對在應(yīng)用的代碼中使用getCurrentInstance。請不要把它當(dāng)作在組合式 API 中獲取this的替代方案來使用。
說白了,這個方法 適合在開發(fā)組件庫的情況下使用,不適合日常業(yè)務(wù)開發(fā)中使用。
getCurrentInstance **只能在 setup 或生命周期鉤子中調(diào)用。**
在 <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 = []
// 注冊組件
function registrationCom(com) {
childrenList.push(com)
}
function handleClick() {
if (childrenList.length > 0) {
childrenList.forEach(item => {
console.log('組件實例:', 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ù)制到你的項目中運行試試看,最好還是敲一遍咯。
Vuex
Vuex 主要解決 跨組件通信 的問題。
在 Vue3 中,需要使用 Vuex v4.x 版本。
安裝
用 npm 或者 Yarn 安裝到項目中。
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ù)的,有點像computed的用法(個人覺得)。mutations: 更改state數(shù)據(jù)的方法都要寫在mutations里。actions:異步異步異步,異步的方法都寫在這里,但最后還是需要通過mutations來修改state的數(shù)據(jù)。modules:分包。如果項目比較大,可以將業(yè)務(wù)拆散成獨立模塊,然后分文件管理和存放。
然后在 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 是有點像的。
比如我們需要過濾一下數(shù)據(jù),或者返回時組裝一下數(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請求
setTimeout(() => {
context.commit('changeMsg', '鯊魚辣椒')
}, 1000)
}
}
})
組件
// xxx.vue
<script setup>
import { useStore } from 'vuex'
const store = useStore()
store.dispatch('fetchMsg')
</script>
Module
Module 就是傳說中的分包了。這需要你將不同模塊的數(shù)據(jù)拆分成一個個 js 文件。
我舉個例子,目錄如下
store |- index.js |- modules/ |- user.js |- goods.js
index.js對外的出口(主文件)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
然后在各個模塊里放入相應(yīng)的數(shù)據(jù)和方法就行。
在組建中調(diào)用方法和訪問數(shù)據(jù),都和之前的用法差不多的。
以上就是 Vuex 的基礎(chǔ)用法。除此之外,Vuex 還有各種語法糖,大家可以自行查閱 官方文檔
Pinia
Pinia 是最近比較火熱的一個工具,也是用來處理 跨組件通信 的,極大可能成為 Vuex 5 。
從我使用 Pinia 一陣后的角度來看,Pinia 跟 Vuex 相比有以下優(yōu)點:
- 調(diào)用時代碼跟簡潔了。
- 對
TS更友好。 - 合并了
Vuex的Mutation和Action。天然的支持異步了。 - 天然分包。
除此之外,Pinia 官網(wǎng)還說它適用于 Vue2 和 Vue3。但我沒試過在 Vue2 中使用 我懶得試。
Pinia 簡化了狀態(tài)管理模塊,只用這3個東西就能應(yīng)對日常大多任務(wù)。
state:存儲數(shù)據(jù)的倉庫getters:獲取和過濾數(shù)據(jù)(跟computed有點像)actions:存放 “修改state”的方法
我舉個簡單的例子
安裝
npm install pinia # 或 yarn add pinia
注冊
在 src 目錄下創(chuàng)建 store 目錄,再在 store 里創(chuàng)建 index.js 和 user.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>
啰嗦兩句
其實 Pinia 的用法和 Vuex 是挺像的,默認(rèn)就是分包的邏輯,在這方面我支持 菠蘿(Pinia)。
Pinia 還提供了多種語法糖,強烈建議閱讀一下 官方文檔。
mitt.js
我們前面用到的 總線 Bus 方法,其實和 mitt.js 有點像,但 mitt.js 提供了更多的方法。
比如:
on:添加事件emit:執(zhí)行事件off:移除事件clear:清除所有事件
mitt.js 不是專門給 Vue 服務(wù)的,但 Vue 可以利用 mitt.js 做跨組件通信。
安裝
npm i mitt
使用
我模擬一下 總線Bus 的方式。
我在同級目錄創(chuàng)建3個文件用作模擬。
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>
此時,點擊 Child.vue 上的按鈕,在控制臺就會執(zhí)行在 Parent.vue 里定義的方法。
mitt.js 的用法其實很簡單,建議跟著 官方示例 敲一下代碼,幾分鐘就上手了。
到此這篇關(guān)于Vue3中10多種組件通訊方法小結(jié)的文章就介紹到這了,更多相關(guān)Vue3 組件通訊內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于實現(xiàn)Vue3版抖音滑動插件踩坑指南
這篇文章主要給大家介紹了關(guān)于實現(xiàn)Vue3版抖音滑動插件踩坑指南,文中通過實例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用vue3具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2022-02-02
淺談vue-lazyload實現(xiàn)的詳細(xì)過程
本篇文章主要介紹了淺談vue-lazyload實現(xiàn)的詳細(xì)過程,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08
VUEJS實戰(zhàn)之利用laypage插件實現(xiàn)分頁(3)
這篇文章主要為大家詳細(xì)介紹了VUEJS實戰(zhàn)之修復(fù)錯誤并且美化時間,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-06-06

