1. 程式人生 > 實用技巧 >nuxt中使用Vuex

nuxt中使用Vuex

引言

在nuxt中使用vuex,以模組方式引用——計數器為例

目錄結構

js模組寫法

// user.js
// state為一個函式, 注意箭頭函式寫法
const state = () => ({
counter: 6
})

// mutations為一個物件
const mutations = {
increment(state) {
state.counter++
},
decrement(state) {
state.counter--
}
}
const actions = {

}
const getters = {

}
export default {
namespace: true, // 名稱空間
state,
mutations,
actions,
getters
}

如果沒有namespace,那麼預設地每一個xxx.vue檔案都會與store資料夾下的xxx.js相對應

vue寫法

1. 直接獲取

直接從user.js模組中獲取state

<!-- user.vue -->
<div class="display-1">{{this.$store.state.user.count}}</div>

2. computed獲取

用computed監聽Vuex中state的變化, 及時渲染到介面上。如果在data中接收Vuex的state, 那麼有可能監聽不到state的變化[1], 一句話就是用computed接受Vuex的狀態

computed介紹:

  1. 用於變數或方法的複雜邏輯, 如vue官網的反轉字串例子
  2. 相較於methods, computed有快取機制, 相同的結果不會重複計算, 而methods中的方法是每次呼叫都會計算
// 從vuex中引入mapState
import { mapState } from 'vuex'
<!-- user.vue html部分 -->
<div class="display-1">{{counter}}</div>
<div class="display-1">{{tag}}</div>
// user.vue computed部分 第一種寫法
computed:mapState('user', {
counter: state => state.counter // 注意寫法,沒中括號
}),
// user.vue computed部分 第二種寫法, 普通函式
computed:mapState('user', {
counter: function(state) {
return state.counter
}
}),
// user.vue computed部分 第三種寫法
computed:mapState("user", ['counter'])
// user.vue computed部分 第四種寫法
// 方法與mapState共存
computed:{
tag(){ // 方法
return 'something'
},
...mapState('user', {
counter: function(state) {
return state.counter
}
}),
}

mapState({}|[])函式, 專門用來接收來自Vuex中的state, 接受一個物件或者一個數組,

...mapState()介紹:

因為mapState()不能直接寫進computed物件中, 而computed的方法必須寫進computed物件中, 所以為了讓方法和state共存引入...即...mapState()寫法誕生

...為物件擴充套件符, 加上之後就可以在computed這個物件中與其他方法共存,沒有方法時可以直接上第一、二種寫法

觸發mutations

// 觸發mutations方式
this.$store.commit("mutationName", [parameter])
// mutations為一個物件
const mutations = {
increment(state) {
state.counter++
},
decrement(state) {
state.counter--
}
}

vi設計http://www.maiqicn.com 辦公資源網站大全https://www.wode007.com

程式碼

index.vue中引用user.js模組

// index.vue
<template>
<div id="index">
<div class="display-1">
<b-icon icon="person"></b-icon>
<b-icon icon="person-fill"></b-icon>
<b-icon icon="triangle"></b-icon>
</div>
<div class="display-1">{{counter}}</div>
<div class="display-1">{{tag}}</div>
<div>
<b-button variant="outline-success" @click="increment">增加</b-button>
<b-button variant="outline-success" @click="decrement">減少</b-button>
</div>
</div>
</template>

<script>
import { mapState } from 'vuex'
export default {
// 初始化時觸發mutations
fetch({ store }) {
store.commit('user/increment')
},
mounted() {},
data() {
return {}
},
methods: {
increment() {
this.$store.commit('user/increment')
},
decrement() {
this.$store.commit('user/decrement')
}
},
computed: {
tag(){
return 'something'
},
...mapState('user', {
counter: state => state.counter
})
},
components: {}
}
</script>

<style scoped>
#index {
min-height: 100%;
}
</style>