溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

nuxt框架中對vuex進行模塊化設(shè)置的實現(xiàn)方法

發(fā)布時間:2020-08-29 05:28:48 來源:腳本之家 閱讀:597 作者:程南風(fēng) 欄目:web開發(fā)
1.Nuxt里怎么使用vuex?

Nuxt.js 內(nèi)置引用了 vuex 模塊,所以不需要額外安裝。

Nuxt.js 會嘗試找到應(yīng)用根目錄下的 store 目錄,如果該目錄存在,它將做以下的事情:
1.1> 引用 vuex 模塊
1.2> 將 vuex 模塊 加到 vendors 構(gòu)建配置中去
1.3> 設(shè)置 Vue 根實例的 store 配置項

Nuxt.js 支持兩種使用 store 的方式:
普通方式: store/index.js 返回一個 Vuex.Store 實例
模塊方式: store 目錄下的每個.js 文件會被轉(zhuǎn)換成為狀態(tài)樹指定命名的子模塊 (當(dāng)然,index 是根模塊)

nuxt框架中對vuex進行模塊化設(shè)置的實現(xiàn)方法

2.Nuxt中怎么對vuex進行模塊化設(shè)置?

2.1> 例如 -- 設(shè)置index.js為根模塊,child1.js與child2.js兩個子模塊

nuxt框架中對vuex進行模塊化設(shè)置的實現(xiàn)方法

2.2> 在store/index.js 中不需要返回 Vuex.Store 實例,可以直接將 state、mutations 和 actions 暴露出來:
(以下為例:index中存儲商品總價,child1中存儲單價,child2中存放數(shù)量)

export const state = () =>({
 totalPrice:0,
});
export const mutations = {
 totalPrice (state) { //總價
 // state.totalPrice = state.num*state.price 錯誤方式:使用子模塊的state,應(yīng)該在變量名前加上文件名,如下
 state.totalPrice = state.child1.price*state.child2.num //正確方式
 }
};

子模塊中同樣直接將 state、mutations 和 actions 暴露出來:

child1.js1
export const state = () =>({
 price:10, //單價
});
export const mutations = {
 getPrice(state,price) { 
 state.price= price
 }
};
child2.js2
export const state = () =>({
 num:5,
});
export const mutations = {
 getNum(state,num) { //數(shù)量
 state.num= num
 }
};
3.在vue文件中獲取vuex的數(shù)據(jù),調(diào)用mutation中的方法修改數(shù)據(jù)
<script>
export default {
 name : 'test',
 data() {
 return {
 totalPrice:this.$store.state.totalPrice, //取index.js(根模塊)中的值
 num:this.$store.state.child2.num,  //取子模塊中的值
 price:this.$store.state.child1.price, //取子模塊中的值
 }
 },
}
</script>
 methods: {
 setTotalPrice(){
 this.$store.commit('totalPrice')
 },
 setNum(){
 this.$store.commit('child2/getNum',參數(shù)) //使用子模塊的mutation中的方法 this.$store.commit(‘文件名/方法名',參數(shù))
 },
 setPrice(){
 this.$store.commit('child1/getPrice',參數(shù)) //使用子模塊的mutation中的方法
 },
 },
補充: 使用子模塊的action: this.$store.dispatch(‘文件名/變量名')

參考鏈接:
https://www.jb51.net/article/169502.htm
https://www.jb51.net/article/169504.htm

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI