Vue3的10種組件通信方式總結(jié)
引言
本文講解 Vue 3.2 組件多種通訊方式的基礎(chǔ)用法,并且使用了 單文件組件 <script setup> 。
眾所周知,Vue.js 中一個(gè)很重要的知識(shí)點(diǎn)是組件通信,不管是業(yè)務(wù)類的開發(fā)還是組件庫開發(fā),都有各自的通訊方法。
本文適合:
- 有 Vue 3 基礎(chǔ)的讀者。
- 打算開發(fā)組件庫的讀者。
本文會(huì)涉及的知識(shí)點(diǎn):
- Props
- emits
- expose / ref
- Non-Props
- v-model
- 插槽 slot
- provide / inject
- 總線 bus
- getCurrentInstance
- Vuex
- Pinia
- 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>
父組件
// 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)!
emits
子組件通知父組件觸發(fā)一個(gè)事件,并且可以傳值給父組件。(簡(jiǎn)稱:子傳父)
父組件
// 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ù)。
用例子說話
父組件
// 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。
還是舉個(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>
打開控制臺(tái)可以看到,屬性被掛到 HTML 元素上了。
多個(gè)元素的情況
但在 Vue3 中,組件已經(jīng)沒規(guī)定只能有一個(gè)根元素了。如果子組件是多個(gè)元素時(shí),上面的例子就不生效了。
// Child.vue <template> <div>子組件:打開控制臺(tái)看看</div> <div>子組件:打開控制臺(tái)看看</div> </template>
此時(shí)可以使用 $attrs 的方式進(jìn)行綁定。
// Child.vue <template> <div :message="$attrs.msg">只綁定指定值</div> <div v-bind="$attrs">全綁定</div> </template>
v-model
v-model 是 Vue 的一個(gè)語法糖。在 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 傳進(jìn)來的值,必須用 modelValue 這個(gè)名字來接收 ]) const emit = defineEmits(['update:modelValue']) // 必須用 update:modelValue 這個(gè)名字來通知父組件修改值 function handleClick() { // 參數(shù)1:通知父組件修改值的方法名 // 參數(shù)2:要修改的值 emit('update:modelValue', '噴射河馬') } </script>
你也可以這樣寫,更加簡(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 綁定
父組件
// 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ǔ)用法非常簡(jiǎn)單,只需在 子組件 中使用 <slot> 標(biāo)簽,就會(huì)將父組件傳進(jìn)來的 HTML 內(nèi)容渲染出來。
父組件
// Parent.vue <template> <Child> <div>雷猴啊</div> </Child> </template>
子組件
// Child.vue <template> <div> <slot></slot> </div> </template>
具名插槽
具名插槽 就是在 默認(rèn)插槽 的基礎(chǔ)上進(jìn)行分類,可以理解為對(duì)號(hào)入座。
父組件
// 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)該就能很好的理解什么叫作用域插槽。
父組件
// 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í),使用 props 和 emit 的方式會(huì)顯得比較笨拙。這時(shí)就可以用 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() { // 這樣寫不合適,因?yàn)関ue里推薦使用單向數(shù)據(jù)流,當(dāng)父級(jí)使用readonly后,這行代碼是不會(huì)生效的。沒使用之前才會(huì)生效。 // name.value = '雷猴' // 正確的方式 changeName('虎軀一震') // 因?yàn)?msg 沒被 readonly 過,所以可以直接修改值 msg.value = '世界' } </script>
provide 可以配合 readonly 一起使用,詳情可以看上面例子和注釋。
provide 和 inject 其實(shí)主要是用在深層關(guān)系中傳值,上面的例子只有父子2層,只是為了舉例說明 我懶。
總線 bus
在 Vue2 有總線傳值的方法,我們?cè)?Vue3 中也可以自己模擬。
這個(gè)方式其實(shí)有點(diǎn)像 Vuex 或者 Pinia 那樣,弄一個(gè)獨(dú)立的工具出來專門控制數(shù)據(jù)。
但和 Vuex 或 Pinia 相比,我們自己寫的這個(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
getcurrentinstance 是 vue 提供的一個(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)用。
在 <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ù)倉(cāng)庫,用來存數(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 跟 Vuex 相比有以下優(yōu)點(diǎn):
- 調(diào)用時(shí)代碼跟簡(jiǎn)潔了。
- 對(duì) TS 更友好。
- 合并了 Vuex 的 Mutation 和 Action 。天然的支持異步了。
- 天然分包。
除此之外,Pinia 官網(wǎng)還說它適用于 Vue2 和 Vue3。但我沒試過在 Vue2 中使用 我懶得試。
Pinia 簡(jiǎn)化了狀態(tài)管理模塊,只用這3個(gè)東西就能應(yīng)對(duì)日常大多任務(wù)。
- state:存儲(chǔ)數(shù)據(jù)的倉(cāng)庫
- 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.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>
啰嗦兩句
其實(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 做跨組件通信。
安裝
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)單,建議跟著 官方示例 敲一下代碼,幾分鐘就上手了。
總結(jié)
到此這篇關(guān)于Vue3的10種組件通信方式的文章就介紹到這了,更多相關(guān)Vue3組件通信方式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue2路由方式--嵌套路由實(shí)現(xiàn)方法分析
這篇文章主要介紹了vue2嵌套路由實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析了vue2嵌套路由基本實(shí)現(xiàn)方法與操作注意事項(xiàng),需要的朋友可以參考下2020-03-03Vue3中的ref為何要用.value進(jìn)行值的調(diào)用呢
這篇文章主要介紹了Vue3中的ref為何要用.value進(jìn)行值的調(diào)用,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09Vue中axios的封裝(報(bào)錯(cuò)、鑒權(quán)、跳轉(zhuǎn)、攔截、提示)
這篇文章主要介紹了Vue中axios的封裝(報(bào)錯(cuò)、鑒權(quán)、跳轉(zhuǎn)、攔截、提示),本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-08-08Vue初始化中的選項(xiàng)合并之initInternalComponent詳解
這篇文章主要介紹了Vue初始化中的選項(xiàng)合并之initInternalComponent的相關(guān)知識(shí),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06Vue3進(jìn)階主題Composition API使用詳解
這篇文章主要為大家介紹了Vue3進(jìn)階主題Composition API使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04vue form表單使用resetFields函數(shù)出現(xiàn)的問題
這篇文章主要介紹了vue form表單使用resetFields函數(shù)出現(xiàn)的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05Vue實(shí)現(xiàn)騰訊云點(diǎn)播視頻上傳功能的實(shí)現(xiàn)代碼
這篇文章主要介紹了Vue實(shí)現(xiàn)騰訊云點(diǎn)播視頻上傳功能的實(shí)現(xiàn)代碼,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08