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 什么時候更新,組件都將同步更新

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

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/278547.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/278547.shtml
英文地址,請注明出處:http://en.pswp.cn/news/278547.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

linux自學(四)之開始centos學習,網絡配置

上一篇&#xff1a;linux自學&#xff08;三&#xff09;之開啟虛擬機 安裝好鏡像之后&#xff0c;重啟之后需要登錄&#xff0c;我這里直接是root賬號直接登錄的&#xff0c;注意&#xff1a;輸入密碼的時候不顯示。 之后輸入ifconfig最常用的命令來查看網卡信息&#xff0c;出…

k8s extender_Windows Home Server的Drive Extender的9種選擇

k8s extenderNow that Microsoft has officially killed off the best part about Windows Home Server what can you do? Here are some alternatives for drive extender that you can use if you want to build a WHS of your own. 既然Microsoft正式取消了Windows Home Se…

為什么element的el-backtop會不管用,來看這里

<template>Scroll down to see the bottom-right button.<el-backtop target".page-component__scroll .el-scrollbar__wrap"></el-backtop> </template>把target指向你要產生“回到頂部”按鈕的組件&#xff0c; 這個組件一定要是產生滾動條…

如何創建一份springboot的docker鏡像

2019獨角獸企業重金招聘Python工程師標準>>> FROM centos:7 ENV JAVA_HOME /usr/java/jdk1.7.0_55 ENV MAC_PUBLISH_PATH /home/app ENV LOG_PATH /var/log ENV PATH $JAVA_HOME/bin:$PATH ENV TIME_ZONE Asia/Shanghai COPY jdk-7u55-linux-x64.rpm /opt/ RUN mkd…

Xamarin.Android 開發中遇到旋轉屏幕錯誤

錯誤信息 : System.NotSupportedException: Unable to find the default constructor on type App5.MyFragment. Please provide the missing constructor. 錯誤圖片&#xff1a; 解決方法&#xff1a;干脆不讓他旋轉屏幕&#xff0c;當下QQ、微信等app都沒有旋轉等功能&#…

原生js打印指定節點元素

很簡單&#xff08;可粘貼至txt文檔后改后綴為html打開看效果&#xff09;&#xff1a; <!doctype html> <html lang"en"> <head><meta charset"utf-8"><title>打印</title><meta name"viewport" conte…

Android社會化分享詳解

前言現如今app市場競爭激烈&#xff0c;做app不會放過任何推廣自己的app的渠道&#xff0c;如果app中沒有社會化分享功能&#xff0c;那真的是OUT了&#xff0c;我們先來看下一些app中的分享界面功能吧。現在主流的分享平臺&#xff0c;一般用的都是微信、QQ、微博&#xff0c;…

windows7黑屏修復_如何在Windows 10更新后修復黑屏

windows7黑屏修復RealVector/Shutterstock.comRealVector / Shutterstock.comSome Windows 10 PCs have been rebooting to a black screen after installing the June 2019 cumulative update from Windows Update. This seems scary at first, but luckily there’s a quick …

[sol]250OJ 1~10

下載 轉載于:https://www.cnblogs.com/yztblog/p/10208314.html

vue/cli4 創建vue項目選項詳解

多版本創建項目一、vue-cli2.x二、vue-cli3.x三、vue-cli4.x1.查看 vue 版本&#xff1a; 項目中,找到package.json文件夾 找"dependencies"中的vue &#xff1b; 若無項目&#xff0c;在cmd中輸入 where vue&#xff0c;cd到vue目錄下輸入 npm list vue &#xff0c…

java 商品評價計算算法

import java.io.Serializable; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.math.BigDecimal; import java.math.RoundingMode;/*** 商品評價算法* * project icomment* fileName ProductScore.java* Description* author light-z…

rainmeter使用教程_如何使用Rainmeter在桌面上顯示報價

rainmeter使用教程I’ve never really been a desktop gadgets and widgets type of person, but I often put an inspirational quote on my desktop wallpaper. Today we’ll show you how to do this using Rainmeter, no matter what wallpaper you switch to. 我從來沒有真…

Some code changes cannot be hot swapped into a running virtual machine

java運行中修改代碼不能改變立刻應用到本次運行中轉載于:https://www.cnblogs.com/Pusteblume/p/10211110.html

自定義v-drag指令(橫向拖拽滾動)

指令 Vue.directive(drag, {// 鉤子函數&#xff0c;被綁定元素插入父節點時調用 (父節點存在即可調用&#xff0c;不必存在于 document 中)。inserted: (el, binding, vnode, oldVnode) > {console.log(el, binding, vnode, oldVnode)let drag el; // 要拖拽的元素// let …

javascript獲取時間差

function GetDateDiff(startTime, endTime, diffType) {//將xxxx-xx-xx的時間格式&#xff0c;轉換為 xxxx/xx/xx的格式 startTime startTime.replace(/\-/g, "/");endTime endTime.replace(/\-/g, "/");//將計算間隔類性字符轉換為小寫diffType diffTy…

JMeter擴展JMeter插件獲取更多監聽器

為了獲取更多監聽器&#xff0c;方便的監控系統及應用&#xff0c;有必要安裝第三方插件 插件下載地址&#xff1a; https://jmeter-plugins.org/downloads/old/ http://pan.baidu.com/s/1gfC11yN 注&#xff1a;如果插件和軟件版本不兼容&#xff0c;可能在開啟Jmeter時會報錯…

如何阻止Chrome(或Edge)接管媒體密鑰

Google Chrome now has built-in support for media keys. Unfortunately, Chrome will take over your media keys and prevent them from controlling apps like Spotify when you’re watching YouTube, for example. Here’s how to make Chrome ignore your media keys. G…

js滾動條滾動到指定元素

let item document.getElementById("item"); // 指定的元素 let wrapper document.getElementById("wrapper"); // 其父元素 - 必須是產生滾動條的元素// 元素聚焦法定位 // item.focus(); // 可用 outline:none; 除去聚焦產生的框; 對于默認沒有聚焦的…

開源性能測試工具JMeter快速入門(一)

目錄一、JMeter簡介二、JMeter功能介紹三、JMeter腳本四、關于JMeter小提示一、JMeter簡介1.定義JMeter是Apache組織開發的基于Java的壓力測試工具。用于對軟件做壓力測試&#xff0c;它最初被設計用于Web應用測試&#xff0c;但后來擴展到其他測試領域。 1&#xff09;它可以用…

八重州8900如何解鎖_八重貴族怪胎之路

八重州8900如何解鎖Dealing with computers day in and day out can be a harrowing experience. In difficult times, or even when things are idle, finding some spirituality can help cope with the experience—Techies: I give you the Eightfold Noble Geek Path. 日…