深入了解Vue.js中的Vuex狀態(tài)管理模式
Vuex
Vuex 是一個專為 Vue.js 開發(fā)的狀態(tài)管理模式。主要是是做數(shù)據(jù)交互,父子組件傳值可以很容易辦到,但是兄弟組件間傳值(兄弟組件下又有父子組件),頁面多并且一層嵌套一層的傳值,非常麻煩,這個時候我們就用vuex來維護共有的狀態(tài)或數(shù)據(jù)。
vuex一共有五大核心概念
1.state: 用來定義數(shù)據(jù)的(相當(dāng)于data),在頁面中用獲取定義的數(shù)據(jù)用:
this.$store.state.變量名
getters:計算屬性(相當(dāng)于vue中的computed),依賴于緩存,只有緩存中的數(shù)據(jù)發(fā)生變化才會重新計算。getters中的方法接收一個state對象作為參數(shù)。
如: state:{ count: 1 }, getters:{ getCount(state) { return state.count + 1 } },
在頁面中獲取用:
this.$store.getters.getCount <h2>{{this.$store.getters.getCount}}</h2>
mutations:是修改 state 值的唯一方法,它只能是同步操作
在頁面中獲取用:
this.$store.commit("方法名") //可以向 store.commit 傳入額外的參數(shù),即 mutation 的 載荷(payload) store.commit('increment', 10) // ... mutations: { increment (state, n) { state.count += n } }
actions:提交的是 mutations,而不是直接變更狀態(tài),它可以包含任意異步操作
modules: 模塊,Vuex允許將store分割成模塊,每個模塊都擁有自己的state,getters,mutations,actions,甚至嵌套模塊。可以避免變量名相同而導(dǎo)致程序出現(xiàn)問題。
const moduleA = { state: {}, mutations: {}, actions: {}, getters: {} } const moduleB = { state: {}, mutations: {}, actions: {}, getters: {} } export default new Vuex.Store({ modules: { a: moduleA, b: moduleB } }) // 在各自的模塊內(nèi)部使用 state.price // 這種使用方式和單個使用方式一樣,直接使用就行 //在組件中使用 store.state.a.price // 先找到模塊的名字,再去調(diào)用屬性 store.state.b.price // 先找到模塊的名字,再去調(diào)用屬性
使用
安裝vuex
npm install --save vuex
配置vuex
在src文件夾下新增一個store文件夾,里面添加一個index.js文件
然后在main.js中引入store文件下的index.js
// main.js內(nèi)部對vuex的配置 import store from '@/store/index.js' new Vue({ el: '#app', store, // 將store暴露出來 template: '<App></App>', components: { App } });
之后我們開始進行store文件下的index.js配置
import Vue from 'vue'; //首先引入vue import Vuex from 'vuex'; //引入vuex Vue.use(Vuex) export default new Vuex.Store({ state: { // state 類似 data //這里面寫入數(shù)據(jù) }, getters:{ // getters 類似 computed // 在這里面寫個方法 }, mutations:{ // mutations 類似methods // 寫方法對數(shù)據(jù)做出更改(同步操作) }, actions:{ // actions 類似methods // 寫方法對數(shù)據(jù)做出更改(異步操作) } })
舉例:
在store中定義商品的原價,計算折扣價,根據(jù)用戶輸入的數(shù)量和商品原價計算出總價
【1】我們約定store中的數(shù)據(jù)是以下形式
import Vue from 'vue'; //首先引入vue import Vuex from 'vuex'; //引入vuex Vue.use(Vuex) export default new Vuex.Store({ state: { price: 100, // 原價 total: '', // 總價 }, getters:{ // 折扣價 discount(state, getters) { return state.price*0.8 } }, mutations:{ // 計算總價:第一個參數(shù)為默認(rèn)參數(shù)state, 后面的參數(shù)為頁面操作傳過來的參數(shù) getTotal(state, n) { return state.total = state.price * n; } }, actions:{ // 這里主要是操作異步操作的,使用起來幾乎和mutations方法一模一樣 // 除了一個是同步操作,一個是異步操作,一個使用commit調(diào)用,一個使用dispatch調(diào)用 // 這里就不多介紹了,有興趣的可以自己去試一試, // 比如你可以用setTimeout去嘗試一下 } })
【2】在頁面中使用store中的數(shù)據(jù)
```javascript <template> <div> <p>原價:{{price}}</p> <p>8折:{{discount}}</p> <p>數(shù)量:<input type="text" v-model="quantity"></p> <p>總價:{{total}}</p> <button @click="getTotal">計算總價</button> </div> </template> <script> export default { data() { return { quantity: 0, } }, computed: { price() { return this.$store.state.price }, discount() { return this.$store.getters.discount }, total() { return this.$store.state.total } }, mounted() { }, methods: { getTotal() { this.$store.commit('getTotal', this.quantity) } }, } </script>
【3】頁面效果
再舉例應(yīng)用場景:
比如登錄頁面,既可以用手機號驗證碼登錄,也可以用手機號密碼登錄,進行切換的時候想保留輸入的手機號碼,這個時候我們可以用vuex。
頁面刷新數(shù)據(jù)丟失問題
vuex存儲的數(shù)據(jù)作為全局的共享數(shù)據(jù),是保存在運行內(nèi)存中的,當(dāng)頁面刷新時,會重新加載vue實例,vuex里的數(shù)據(jù)會重新初始化,從而導(dǎo)致數(shù)據(jù)丟失。
怎么解決?
直接在vuex修改數(shù)據(jù)方法中將數(shù)據(jù)存儲到瀏覽器緩存中(sessionStorage、localStorage、cookie)
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({ state: { orderList: [], menuList: [] }, mutations: { orderList(s, d) { s.orderList= d; window.localStorage.setItem("list",jsON.stringify(s.orderList)) }, menuList(s, d) { s.menuList = d; window.localStorage.setItem("list",jsON.stringify(s.menuList)) }, } })
在頁面加載時再從本地存儲中取出并賦給vuex
if (window.localStorage.getItem("list") ) { this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(window.localStorage.getItem("list")))) }
到此這篇關(guān)于深入了解Vue.js中的Vuex狀態(tài)管理模式的文章就介紹到這了,更多相關(guān)Vuex狀態(tài)管理模式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue?element?ui表格相同數(shù)據(jù)合并單元格效果實例
工作中遇到需要根據(jù)單元格某個屬性合并,特此記錄下,下面這篇文章主要給大家介紹了關(guān)于vue?element?ui表格相同數(shù)據(jù)合并單元格效果的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-11-11vue+element表格實現(xiàn)多層數(shù)據(jù)的嵌套方式
這篇文章主要介紹了vue+element表格實現(xiàn)多層數(shù)據(jù)的嵌套方式,具有很好的參考價值。希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09vue+springboot用戶注銷功能實現(xiàn)代碼
這篇文章主要介紹了vue+springboot用戶注銷功能,本文通過示例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-05-05