VUE狀態管理 store

2021-10-25 18:43:59 字數 1934 閱讀 7836

管理全域性變數,便於元件之間傳值

1、在store資料夾中新建index.js檔案

import vue from 'vue'    //引入vue

import vuex from 'vuex' //引入vue

//使用vuex

vue.use(vuex)

//建立vuex例項

const store = new vuex.store(

})export default store //匯出store

2、在main.js中引用檔案,例項引入store物件

import store from ./store/index

new vue()

資料儲存在index.js檔案中,可使用this.$store.state來獲取自定義資料

相當於vue中的computed計算屬性,getter 的返回值會根據它的依賴被快取起來,且只有當它的依賴值發生了改變才會被重新計算。getters 可以用於監聽、state中的值的變化,返回計算後的結果

this.$store.getters.getstorecount

//頁面中這樣寫可直接呼叫getters中的方法

檔案中定義getters的方法

const store = new vuex.store(,

getters:

}})

用來修改store中的值

//在頁面的方法中呼叫mutation的方法

methos:,

reductionfun()

}

在index.js檔案中新增mutations

const store = new vuex.store(,

getters:

},mutations:,

reduction(state)

}})

雖然上述方法可以修改頁面的值,但是官方並不建議這樣做,我們可以使用action呼叫mutation改變狀態的值

const store = new vuex.store(,

getters:

},mutations:,

reduction(state)

},actions:,

reductionfun(context)

}})

頁面的呼叫如下:

methos:,

reductionfun()

}

若想傳參也依次在呼叫的方法中加入即可

可以使呼叫更加簡潔,不用寫很長

//vue檔案中

//頁面可直接使用自定義變數名}表示

import from 'vuex'

computed:)

}

//將 this.commonactionget() 對映為 this.$store.dispatch('commonactionget')

//這種寫法方法名稱必須對應

...mapactions(['commonactionget', 'commonactiongetjson'])

...mapactions()

1、index.js 定義vuex.store

2、state 相當於資料庫,定義了資料的結構和初始值

3、getters 獲取state中的狀態並返回,但是不能修改

4、actions 提交狀態,呼叫mutations方法對資料進行操作

5、mutations 定義state資料的修改操作

6、mapstate、mapgetters、mapactions、mapmutations 做對映

Vue狀態管理

一 vuex是什麼 二 使用 單向資料流 state const state 使用 this store.state.uid this store.state.nickname getters const getters mutations 不推薦使用 mutations const mutatio...

vue狀態管理vuex

const store new vuex.store mutations changeasync function state,a getters actions 1000 解讀 獲取 this.sto re.s tate nam e th is.store.state.name this.stor...

vue狀態管理vuex

vuex就是提供乙個倉庫,store倉庫裡面放了很多物件。其中state就是資料來源存放地,對應於與一般vue物件裡面的data 後面講到的actions和mutations對應於methods 在使用vuex的時候通常會建立store例項new vuex.store 有很多子模組的時候還會使用到m...