日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > vue >内容正文

vue

Vue使用Vuex一步步封装并使用store

發布時間:2023/12/6 vue 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Vue使用Vuex一步步封装并使用store 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

    • 一、安裝Vuex依賴
    • 二、一步步封裝store
      • 1. main.js中全局引入store倉庫(下一步創建)
      • 2. this.$store
      • 3. this.$store.state
      • 4. this.$store.getters(this. $store.state的升級)
      • 5. this.$store.commit('mutations')
      • 6. this.$store.dispatch('actions')(this. $store.commit('mutations')的升級)
      • 7.strict嚴格模式
    • 三、modules 模塊化
    • 四、使用倉庫
      • 1、無map系列
      • 2、map映射系列
      • 3、總結

精簡版

一、安裝Vuex依賴

cnpm install vuex --save

二、一步步封裝store

1. main.js中全局引入store倉庫(下一步創建)

import store from './store' //引入storenew Vue({el: '#app',router,store, //掛載store,this將自動生成$store屬性template: '<App/>',components: { App } })

掛載store,this將自動生成$store屬性

2. this.$store

創建store倉庫:習慣在src下創建store文件夾,再創建index.js,內容:

import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const store = new Vuex.Store();export default store;

此時你已經有了一個空的store全局倉庫,沒有任何功能,但可以在任何vue實例下使用 this.$store 去訪問它。

  • store使用范圍均是可以全局使用;
  • let a=1; {a:a}.a 的縮寫是 {a}.a,即當字典的鍵和值命名一樣時,可以省略只寫a
  • state、getters、mutations、mutations均是Vuex封裝好的特殊變量,以下聲明的功能變量均是這些名字,一個好處是store掛載該功能時可以簡寫(如3-1,本例均如此)。當然你也可直接在store中寫功能(如3-2)。

3. this.$store.state

給store倉庫讀取數據功能:state

/********* 3-1 **********/ import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex);const state={ //要設置的全局訪問的state對象,賦予初始屬性值themeColor: {val:'blue',opacity:false},changeThemeCount:0,cache:''}; const store = new Vuex.Store({state});export default store;

此時你的store倉庫已經有了存取數據的功能,可以用 this.$store.state.themeColor 等數據了。
下面是第二種寫法

/********* 3-2 **********/ import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex);const store = new Vuex.Store({state:{//要設置的全局訪問的state對象,賦予初始屬性值themeColor: {val:'blue',opacity:false},changeThemeCount:0,cache:''}});export default store;

4. this.$store.getters(this. $store.state的升級)

給state功能升級,讓他擁有計算能力(類似vue中的computed方法):getters:

import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex);const state={ //要設置的全局訪問的state對象,賦予初始屬性值themeColor: {val:'blue',opacity:false},changeThemeCount:0,cache:''}; const getters = { //實時監聽state值的變化(最新狀態)getThemeColor(state) { //定義函數,返回處理過的val,命名最好有代表性let hour = new Date().getHours();// 如果白天則主題色不透明,反之state.themeColor.opacity = 8 <= hour && hour <= 20;return state.themeColor} }; const store = new Vuex.Store({state, // 掛載存取數據功能getters //掛載數據計算功能 }); export default store;

此時使用 this.$store.getters.getThemeColor 獲取顏色,將自動根據時間的不同自動設置主題是否有透明的效果

5. this.$store.commit(‘mutations’)

給store倉庫使用函數功能(只為操作state數據):mutations - 同步

import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex);const state={ //要設置的全局訪問的state對象,賦予初始屬性值themeColor: {val:'blue',opacity:false},changeThemeCount:0,cache:''}; const getters = { //實時監聽state值的變化(最新狀態)getThemeColor(state) { //定義函數,返回處理過的val,命名最好有代表性let hour = new Date().getHours();// 如果白天則主題色不透明,反之state.themeColor.opacity = 8 <= hour && hour <= 20;return state.themeColor} }; const mutations = {//自定義改變state初始值的方法,這里面的參數除了state之外還可以再傳額外的參數(變量或對象);clearCatch(state) { state.cache = "";state.changeThemeCount= 0;},setThemeColor(state,color,opacity){ state.themeColor.val = color;state.themeColor.opacity = opacity;state.changeThemeCount++;} }; const store = new Vuex.Store({state, // 掛載存取數據功能getters, //掛載數據計算功能mutations // 掛載函數功能 }); export default store;

此時可以使用 this.$store.commit(‘setThemeColor’,‘grey’,‘1’) 了(注意第一個參數是函數名,不是傳參給state的,state自己會傳,后兩個才是對應傳參)。可以主動設置主題色和透明度,操作是同步的,即如果你在同一個組件連續調用多次setThemeColor函數,獲取倉庫中state.changeThemeCount的值是一樣的,下面介紹異步函數。

6. this.$store.dispatch(‘actions’)(this. $store.commit(‘mutations’)的升級)

給store倉庫的函數commit功能升級(只為異步操作mutations中的函數):actions - 異步

import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex);const state={ //要設置的全局訪問的state對象,賦予初始屬性值themeColor: {val:'blue',opacity:false},changeThemeCount:0,cache:''}; const getters = { //實時監聽state值的變化(最新狀態)getThemeColor(state) { //定義函數,返回處理過的val,命名最好有代表性let hour = new Date().getHours();// 如果白天則主題色不透明,反之state.themeColor.opacity = 8 <= hour && hour <= 20;return state.themeColor} }; const mutations = {//自定義改變state初始值的方法,這里面的參數除了state之外還可以再傳額外的參數(變量或對象);clearCatch(state) { state.cache = "";state.changeThemeCount= 0;},setThemeColor(state,color,opacity){ state.themeColor.val = color;state.themeColor.opacity = opacity;state.changeThemeCount++;} }; const actions = {//自定義觸發mutations里函數的方法,context與store 實例具有相同方法和屬性setThemeColorAction(context,color,opacity){context.commit('setThemeColor',color,opacity);} }; const store = new Vuex.Store({state, // 掛載存取數據功能getters, //掛載數據計算功能mutations, // 掛載函數功能actions, // 掛載異步函數 }); export default store;

此時可以使用 this.$store.dispatch(‘setThemeColorAction’,‘grey’,‘1’) 了(注意第一個參數是函數名,不是傳參給context的,context自己會傳,后兩個才是對應傳參)。可以主動設置主題色和透明度,操作是異步的,即如果你在同一個組件連續調用多次setThemeColorAction函數,獲取倉庫中state.changeThemeCount的值就不是一樣的。

7.strict嚴格模式

export default new Vuex.Store({strict: true,state: {...},... }

此模式下所有的狀態變更(即更新state)必須使用mutation(commit),如果在組件中直接修改state則會報錯。這樣的好處是所有的state的更新都體現在倉庫中,整改方便;使用devTools調試工具時可以跟蹤到狀態的修改。

三、modules 模塊化

第二個模塊介紹了store倉庫的四個功能:state、getters、mutations和actions,下面介紹第五個功能:modules。

  • 當項目比較大時,一個store中數據會非常多而復雜,不易管理。此時便可建多個“子倉庫”,分別對應不同模塊做數據的讀取和操作。
  • 注意主倉庫還是那一個,只要把他的“子倉庫”放在主倉庫的modules下即可。
  • 子倉庫看著很像倉庫,其實它并不是store的實例,不是倉庫(new Vuex.Store()實例化后的對象才是倉庫),只是一個普通js對象(字典)。

1、在store下新建modules文件夾,在modules下新建home.js“子倉庫”。

即home.js只管主頁下的數據(一般不要分的太細,最多一個頁面一個倉庫管簡潔),下面是home.js代碼

//home.jsconst state={users:[] //存訪問該頁面的所有用戶 }; const getters={getUsers(state){ //獲取訪問該頁面的所有用戶// 對數據清理-除去臟數據if (state.users.includes('*')) delete state.users['*'] return state.users;} }; const mutations={addUser(state,name){ //增加訪問用戶state.collects.push(name)}}; const actions={invokeAddUser(context,name){ //觸發mutations里面的addUser,傳入數據形參name對應到userscontext.commit('addUser',name);} }; // 注意和倉庫的區別 const store = {// namespaced用于在全局引用此文件里的方法時標識這一個的文件名,使得讓人明白這些數據來自哪個倉庫// 即當你需要在別的文件里面使用子倉庫(mapStates、mapGetters、mapActions)時,里面的方法需要注明來自哪一個模塊的方法namespaced:true,state,getters,mutations,actions } export default store;

2.“子倉庫”創建完成,要讓主倉庫引用它:

import Vue from 'vue'; import Vuex from 'vuex'; import home from './modules/home.js'Vue.use(Vuex);const state={ //要設置的全局訪問的state對象,賦予初始屬性值themeColor: {val:'blue',opacity:false},changeThemeCount:0,cache:''}; const getters = { //實時監聽state值的變化(最新狀態)getThemeColor(state) { //定義函數,返回處理過的val,命名最好有代表性let hour = new Date().getHours();// 如果白天則主題色不透明,反之state.themeColor.opacity = 8 <= hour && hour <= 20;return state.themeColor} }; const mutations = {//自定義改變state初始值的方法,這里面的參數除了state之外還可以再傳額外的參數(變量或對象);clearCatch(state) { state.cache = "";state.changeThemeCount= 0;},setThemeColor(state,color,opacity){ state.themeColor.val = color;state.themeColor.opacity = opacity;state.changeThemeCount++;} }; const actions = {//自定義觸發mutations里函數的方法,context與store 實例具有相同方法和屬性setThemeColorAction(context,color,opacity){context.commit('setThemeColor',color,opacity);} }; const store = new Vuex.Store({state, // 掛載存取數據功能getters, //掛載數據計算功能mutations, // 掛載函數功能actions, // 掛載異步函數modules:{ // 掛載子倉庫home} }); export default store;

此時便有了第一個“子倉庫”了!

四、使用倉庫

1、無map系列

適合使用場景較少:
建好倉庫,組件中直接使用state、getters、mutations、actions:

  • this.$store.state.*
  • this.$store.getters.*
  • this.$store.commit.*
  • this.$store.dispatch.*

2、map映射系列

適合使用場景頻繁:
1、使用mapGetters、mapActions 和 mapStates之前需要import導入:

import {mapState,mapGetters,mapActions} from 'vuex';

2、使用ES6新語法-超引用,將某個功能下的數據或方法全部映射出來以供使用,下面是mapState、mapGetters、mapActions的例子:

//這里的...是超引用,映射內容,可以寫在computed下、methods下等(一般放在開頭)// 直接從庫中取值 - 將庫里的users值返回給字典中的users并映射給this組件...mapState({ users:state=>state.home.users }),// 使用計算屬性 - 將庫里的users計算后的值返回給字典中的users并映射給this組件...mapGetters('home',{ users:'getUsers' //獲取清理后的數據//由于home倉庫 namespaced:true,所以第一個參數作為標識// 不使用標識訪問的是主倉庫})// 使用異步函數 - 以數組中的函數名,從庫中對應的函數映射給this組件以供使用...mapActions('home',['invokeAddUser'])// 有某個組件 <span @click='invokeAddUser(name)'></span>// 或者直接使用 this.invokeAddUser(name)

3、擴展

1、mapState映射的三種寫法computed: mapState({// 箭頭函數可使代碼更簡練count: state => state.count,// 傳字符串參數 'count' 等同于 `state => state.count`countAlias: 'count',// 為了能夠使用 `this` 獲取局部狀態,必須使用常規函數countPlusLocalState (state) {return state.count + this.localCount}})2、當映射的計算屬性的名稱與state的子節點名稱相同時,我們也可以給 mapState傳一個字符串數組。computed: mapState([ // 數組"count"])3、倉庫中action的第二種接收參數 const actions = {//自定義觸發mutations里函數的方法,{commit}與store 實例具有相同方法和屬性setThemeColorAction({commit},color,opacity){commit('setThemeColor',color,opacity);} };

3、總結

1、Vuex 是一個專門為 Vue.js 應用所設計的集中式狀態管理架構。它借鑒了 Flux 和 Redux 的設計思想,但簡化了概念,并且采用了一種為能更好發揮 Vue.js 數據響應機制而專門設計的實現。

2、Vuex 的四個核心概念分別是:
The state tree:Vuex 使用單一狀態樹,用一個對象就包含了全部的應用層級狀態。至此它便作為一個『唯一數據源(SSOT)』而存在。這也意味著,每個應用將僅僅包含一個 store 實例。單狀態樹讓我們能夠直接地定位任一特定的狀態片段,在調試的過程中也能輕易地取得整個當前應用狀態的快照。
Getters: 用來從 store 獲取 Vue 組件數據。
Mutators: 事件處理器用來驅動狀態的變化。
Actions: 可以給組件使用的函數,以此用來驅動事件處理器 mutations

3、Vuex 應用中數據的流向(Vuex 官方圖)

  • 數據流都是單向的
  • 組件能夠調用 action
  • action 用來派發 Mutation
  • 只有 mutation 可以改變狀態
  • store 是響應式的,無論 state 什么時候更新,組件都將同步更新

參考文獻:
思否-飛躍
思否-離塵不理人

總結

以上是生活随笔為你收集整理的Vue使用Vuex一步步封装并使用store的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。