!!! 這個例子可以先忽略mutations
初始化一個state
const store = new Vuex.Store({
state: {
name: "old name",
age: 18,
sex: "女",
},
mutations: {
changName(state) {
state.name = "newName"
},
addAge(state) {
state.age += 1
},
changSex(state) {
state.sex = state.age + "男"
}
}
})
在組件中使用
- 直接賦值給data中的變量
這種情況會導致name直接僅僅接受了一個值,即使點擊了我要改名,name也不會改變。
2 使用computed進行接收
computed會進行監聽,所以只要this.$store.state.age改變,age就會改變。這也是官方推薦的寫法
- 直接在頁面調用顯示
因爲一個store是一個vue實例,所以數據變了,頁面數據也會跟着變
<template>
<div>
<button @click="changeName">我要改名</button>
<button @click="addAge">我長大啦</button>
<button @click="changeName">我要改名</button>
<p>{{this.$store.state.sex}}</p>
<p>{{name}}</p>
<p>{{age}}</p>
</div>
</template>
<script>
export default {
name: "Home",
data() {
return {
name: this.$store.state.name
};
},
computed: {
age() {
return this.$store.state.age;
}
},
methods: {
changeName() {
this.$store.commit("changName");
},
addAge() {
this.$store.commit("addAge");
},
changSex() {
this.$store.commit("changSex");
}
}
};
</script>
mapState 輔助函數
在上面,我們推薦把值放在computed中,這樣會導致一個問題,我們這裏有三個變量,如果都按照上面的寫法,會顯得代碼特別繁雜。
所以vuex提供了一個輔助函數mapState.這個函數會返回一個對象
- 先在組件中引入mapstate
import { mapState } from 'vuex'
- 具體的寫法
三種寫法請參考代碼
computed: mapState({
// 箭頭函數可使代碼更簡練
name: state => state.name,
// 傳字符串參數 'age' 等同於 `state => state.age`
age: 'age',
// 爲了能夠使用 `this` 獲取局部狀態,必須使用常規函數
countPlusLocalState (state) {
return state.name+ data中定義的變量
}
})
- 注意
當映射的計算屬性的名稱與 state 的子節點名稱相同時,我們也可以給 mapState 傳一個字符串數組。
注意這裏方括號,最外層的{}可以省略
computed: {mapState([
// 映射 this.count 爲 store.state.count
"name",
"age",
"sex"
]),}
因爲mapState返回一個對象,所以可以使用展開運算符
computed: {
...mapState({
name: "name",
age: "age",
sex: "sex"
})
},