vuex入門教程,圖文+實(shí)例解析
我理解的概念
vuex是為vue提供了全局的狀態(tài)倉(cāng)庫(kù)(store),就像一個(gè)狀態(tài)機(jī),避免了父子、兄弟組件之前復(fù)雜的傳參。他維持了全局共用的數(shù)據(jù)的一致性。
核心概念秒懂
1,state 共用的數(shù)據(jù)
2,getters 處理state后得到想要的數(shù)據(jù)
3,mutations 唯一可以修改state的函數(shù)
4,actions 只能顯式的調(diào)用mutations,可以異步、請(qǐng)求數(shù)據(jù)
5,moudles 把1、2、3、4包裝起來的當(dāng)成一個(gè)模塊,可以有多個(gè)也可以沒有
不說廢話直接在實(shí)例里面一一解釋
項(xiàng)目結(jié)構(gòu):
安裝
cnpm i vuex -S
創(chuàng)建
創(chuàng)建如圖的store
以下代碼都是moduleA代碼,
state.js
const state = { userInfo: { userName: '秋刀魚笛滋味', age: 28, job: '前端工程師' }, firend: [], girlfirend: [ { name: 'LuoSi', age: 20, nationality: '韓國(guó)' }, { name: 'AnNi', age: 22, nationality: '俄羅斯' } ] } export default state;
state沒啥好解釋的就一個(gè)對(duì)象,放你要用的狀態(tài)碼
getters.js
const getters = { userJob: (state) => { return `${state.userInfo.job}` }, girlfirendInfo: (state, getters) => { const girlfirend = state.girlfirend let info = girlfirend.map((item, index) => { return `${index + 1}號(hào)女友的名字是${item.name},年齡${item.age},來自${item.nationality}` }).join(',') return `一共有${girlfirend.length}個(gè)女友,${info},可怕的是他只是一名${getters.userJob}。` } } export default getters;
getters接受兩個(gè)參數(shù),第一個(gè)是state,第二個(gè)是getters里面其他的函數(shù)
mutation.js
import axios from 'axios'; const mutations = { ageAdd (state, payload) { payload = payload || 1 state.userInfo.age += payload }, addGirlFirend (state, payload) { state.girlfirend.push({ name: payload.name, age: payload.age, nationality: payload.nationality }) }, getFirend (state, payload) { state.firend = payload }, mutfired (state) { //vuex嚴(yán)禁在mutations里面進(jìn)行異步操作,嚴(yán)格模式報(bào)錯(cuò),難于調(diào)試 axios.get('/myServer').then(res => { if (res.status === 200) { state.firend = res.data.data.list } }) } } export default mutations;
mutations接受兩個(gè)參數(shù):state payload(調(diào)用時(shí)攜帶的參數(shù)),他是唯一可以修改state的地方,注意不可異步、不可調(diào)接口,嚴(yán)格模式會(huì)報(bào)錯(cuò)
如圖:
actions.js
import axios from 'axios'; const actions = { addGirlFirend ({ commit, state, getters }, payload) { commit('addGirlFirend', payload); }, getFirends (ctx) { //ctx是store下當(dāng)前module對(duì)象 axios.get('/myServer').then(res => { if (res.status === 200) { ctx.commit('getFirend', res.data.data.list) //直接在actions里面也可以修改state,但是不建議,創(chuàng)建store時(shí)用嚴(yán)格模式,會(huì)報(bào)錯(cuò),不符合vuex單向數(shù)據(jù)流的規(guī)范(只能在mutions里面修改state) // ctx.state.firend = res.data.data.list } }) } } export default actions;
actions接受一個(gè)當(dāng)前module的上下文對(duì)象(常用有commit),用來commit 提交mutations,主要用來請(qǐng)求后端數(shù)據(jù),可以異步
index.js
import state from './state'; import getters from './getters'; import mutations from './mutations.js'; import actions from './actions'; const moduleA = { state, getters, mutations, actions } export default moduleA;
把各個(gè)組件集合起來暴露出模塊
再來看看store的實(shí)例化
store/index.js
import Vuex from 'vuex' import Vue from 'vue' import moduleA from './moduleA'; import moduleB from './moduleB'; Vue.use(Vuex) let store = new Vuex.Store({ //在嚴(yán)格模式下,無論何時(shí)發(fā)生了狀態(tài)變更且不是由 mutation 函數(shù)引起的,將會(huì)拋出錯(cuò)誤。這能保證所有的狀態(tài)變更都能被調(diào)試工具跟蹤到。 //*嚴(yán)格模式會(huì)深度監(jiān)測(cè)狀態(tài)樹來檢測(cè)不合規(guī)的狀態(tài)變更——請(qǐng)確保在發(fā)布環(huán)境下關(guān)閉嚴(yán)格模式,以避免性能損失。 strict: process.env.NODE_ENV !== 'production',//自動(dòng)在生產(chǎn)環(huán)境下關(guān)閉嚴(yán)格模式 modules: { moduleA, moduleB } }) export default store
注意:一定要用Vue.use一下vuex,最好使用嚴(yán)格模式!
當(dāng)然store里面還可以用命名空間和插件,一般項(xiàng)目用不上
掛載store
在項(xiàng)目主文件
main.js 實(shí)例化vue時(shí),掛載
new Vue({ el: '#app', router, store, components: { App }, template: '<App/>' })
直接在實(shí)例里面看怎么快速使用store吧
helloWorld.vue
<template> <div> <Card style="width:550px"> <div slot="title"> <Icon type="ios-film-outline"></Icon> 個(gè)人信息 </div> <div> <p>姓名: {{userInfo.userName}}</p> <p>年齡: {{userInfo.age}}</p> {{girlfirendInfo}} </div> </Card> <hr style="margin:20px 0" /> <Button type="success" @click="ageAdd()">增加了一歲</Button> <hr style="margin:20px 0" /> <Button type="success" @click="addAge">增加了兩歲(commit)</Button> <hr style="margin:20px 0" /> <Card style="width:550px"> <div slot="title"> <Icon type="ios-film-outline"></Icon> 女友信息: </div> <div> 名字: <Input v-model="girlInfo.name"></Input> 年齡:</br> <Input-number :max="100" :min="1" v-model="girlInfo.age"></Input-number></br> 國(guó)籍: <Input v-model="girlInfo.nationality"></Input> </div> <Button type="success" @click="addGirlFirend(girlInfo)">增加</Button> <Button type="success" @click="addGirlFirend1">增加(dispatch)</Button> </Card> <hr style="margin:20px 0" /> <Card style="width:550px"> <div slot="title"> <Icon type="ios-film-outline"></Icon> 朋友信息: </div> <div> <p v-for="item in firend" :key="item.userName">{{item.userName}}</p> </div> <Button type="info" @click="getFirends">獲取朋友</Button> </Card> </div> </template> <script> import { mapState, mapGetters, mapMutations, mapActions } from 'vuex' export default { data () { return { girlInfo: { name: '', age: 18, nationality: '' } } }, computed: { ...mapGetters(['girlfirendInfo']), ...mapState({ userInfo: state => state.moduleA.userInfo, //使用vuex的modules后一定要指明模塊 firend: state => state.moduleA.firend }) }, methods: { ...mapActions(['addGirlFirend', 'getFirends']), //this.$store.dispatch('addGirlFirend',payload) ...mapMutations(['ageAdd']), //this.$store.commit('ageAdd',payload) // 上面兩個(gè)輔助函數(shù)方法的實(shí)質(zhì)跟下面是一樣的,推薦 使用輔助函數(shù) addAge () { this.$store.commit('ageAdd', 2) }, addGirlFirend1 () { this.$store.dispatch('addGirlFirend', this.girlInfo) } } }
先看一下初始UI吧
簡(jiǎn)單解釋一下
主要的4個(gè)模塊,有對(duì)應(yīng)的四個(gè)輔助函數(shù),用處是把狀態(tài) 和 操作映射到當(dāng)前頁(yè)面
mapState
和mapGetters
,是狀態(tài)數(shù)據(jù),放在計(jì)算屬性;mapMutations
和mapActions
是操作函數(shù), 顯然放在方法里面;
注意帶的注釋;
直接看效果吧
調(diào)用mutations
調(diào)用actions
actions調(diào)接口
vuex的問題,解決方法點(diǎn)擊vuex刷新state就沒了
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue實(shí)現(xiàn)移動(dòng)端懸浮窗效果
這篇文章主要為大家詳細(xì)介紹了vue實(shí)現(xiàn)移動(dòng)端懸浮窗效果,vuejs實(shí)現(xiàn)div拖拽移動(dòng),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-12-12從零開始用webpack構(gòu)建一個(gè)vue3.0項(xiàng)目工程的實(shí)現(xiàn)
這篇文章主要介紹了從零開始用webpack構(gòu)建一個(gè)vue3.0項(xiàng)目工程的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09基于vue2.0的活動(dòng)倒計(jì)時(shí)組件countdown(附源碼下載)
這是一款基于vue2.0的活動(dòng)倒計(jì)時(shí)組件,可以使用服務(wù)端時(shí)間作為當(dāng)前時(shí)間,在倒計(jì)時(shí)開始和結(jié)束時(shí)可以自定義回調(diào)函數(shù)。這篇文章主要介紹了基于vue2.0的活動(dòng)倒計(jì)時(shí)組件countdown,需要的朋友可以參考下2018-10-10vue實(shí)現(xiàn)移動(dòng)端適方案的完整步驟
現(xiàn)在的手機(jī)五花八門,造就了移動(dòng)端窗口分辨率繁多的局面,在不同分辨率的屏幕下保持與UI圖一致的效果,就成了讓前端不得不頭疼的問題,下面這篇文章主要給大家介紹了vue實(shí)現(xiàn)移動(dòng)端適方案的相關(guān)資料,需要的朋友可以參考下2022-10-10