具體解析:
computed
:- 這是 Vue 組件選項中的計算屬性,用于聲明依賴于其他數據而存在的派生數據。
- 計算屬性會根據依賴進行緩存,只有當依賴的數據發生變化時才會重新計算。
mapState
:- 這是 Vuex 提供的一個輔助函數,用于將 store 中的 state 映射到組件的計算屬性中。
- 它的作用是簡化手動編寫計算屬性來獲取 store 中狀態的過程。
...
?擴展運算符:- 這里使用 ES6 的擴展運算符,將?
mapState
?返回的對象展開并合并到?computed
?對象中。 - 如果不使用擴展運算符,需要手動將映射的狀態添加到計算屬性中,代碼會更繁瑣。
- 這里使用 ES6 的擴展運算符,將?
['auditObj']
:- 這是一個數組,指定了要從 Vuex store 的 state 中映射的狀態名稱。
- 這里表示要映射名為?
auditObj
?的狀態。
等價寫法:
computed: {auditObj() {
// 把store中存儲共享狀態數據的對象auditObj拿出來全文方便調用return this.$store.state.auditObj;}
}
拓展解析:
一、Vue 的核心特性
響應式數據綁定
Vue 會自動追蹤數據變化,并更新依賴該數據的 DOM,無需手動操作 DOM。
<div id="app"><p>{{ message }}</p><button @click="message = 'Hello Vue!'">點擊修改</button>
</div><script>new Vue({el: '#app',data() {return { message: 'Hello World!' }}})
</script>
二、computed是 Vue 組件選項中的一個特殊配置項
1. computed
?是Vue 組件選項中的計算屬性,會根據依賴進行緩存,只有當依賴的數據發生變化時才會重新計算
2 和方法的調用區別【Computed (有緩存)/Methods (無緩存)】
<template><div><p>Count: {{ count }}</p><button @click="count++">Increase Count</button><p>Computed Time: {{ computedTime }}</p> <!-- 計算屬性 --><p>Method Time: {{ methodTime() }}</p> <!-- 方法調用 --></div>
</template><script>
export default {data() {return {count: 0}},computed: {computedTime() {// 這個計算屬性不依賴任何響應式數據(如 count),所以它只計算一次,永遠返回緩存值return Date.now();}},methods: {methodTime() {// 方法每次都會執行return Date.now();}}
}
</script>
三、Vuex 的mapState函數
1. Vuex 核心概念:store
Vuex 是 Vue.js 官方的狀態管理模式庫,用于集中管理 Vue 應用中多個組件共享的狀態;store
?是 Vuex 的核心容器,它封裝了應用的共享狀態(state)?和操作狀態的方法。
特點:
- 整個應用只有一個唯一的?
store
(單例模式) - 包含?
state
(狀態)、mutations
(同步修改)、actions
(異步操作)、getters
(派生狀態)等核心模塊 - 組件通過?
store
?訪問或修改共享狀態
- 整個應用只有一個唯一的?
創建方式:
import Vue from 'vue' import Vuex from 'vuex'Vue.use(Vuex)const store = new Vuex.Store({// 核心配置項state: { ... }, // 狀態mutations: { ... }, // 同步修改狀態actions: { ... }, // 異步操作getters: { ... }, // 計算屬性modules: { ... } // 模塊拆分(復雜應用) })export default store
2.?
state
:存儲共享狀態的數據state
?是?store
?中存儲共享狀態數據的對象,相當于組件中?data
?的全局版本。
? ? ? ?基本用法:
const store = new Vuex.Store({state: {count: 0, // 基礎類型user: { name: 'John' }, // 對象類型todos: ['Learn Vuex'] // 數組類型}
})
? ? 組件中訪問?state
:通過?this.$store.state.xxx
?直接訪問:
// 組件中
export default {counted() {console.log(this.$store.state.count) // 輸出 0console.log(this.$store.state.user.name) // 輸出 'John'}
}
3.?mapState
:映射?state
?到組件的輔助函數
mapState
?是 Vuex 提供的輔助函數,用于將?store.state
?中的屬性映射到組件的計算屬性(computed
)中,簡化代碼。當組件需要訪問多個?state
?屬性時,避免重復編寫?this.$store.state.xxx
。
數組形式(適用于屬性名與?
state
?中一致):
import { mapState } from 'vuex';export default {computed: {...mapState(['count', 'auditObj'])
}
上面等同于
export default {computed: {count() {return this.$store.state.count; // 重復寫 this.$store.state},user() {return this.$store.state.auditObj; // 重復寫 this.$store.state}}
}
- 對象形式(適用于需要重命名或復雜映射):
export default {computed: {...mapState({myCount: 'count'})}
}