vuex入門教程,圖文+實例解析
我理解的概念
vuex是為vue提供了全局的狀態(tài)倉庫(store),就像一個狀態(tài)機,避免了父子、兄弟組件之前復雜的傳參。他維持了全局共用的數(shù)據(jù)的一致性。
核心概念秒懂
1,state 共用的數(shù)據(jù)
2,getters 處理state后得到想要的數(shù)據(jù)
3,mutations 唯一可以修改state的函數(shù)
4,actions 只能顯式的調用mutations,可以異步、請求數(shù)據(jù)
5,moudles 把1、2、3、4包裝起來的當成一個模塊,可以有多個也可以沒有
不說廢話直接在實例里面一一解釋
項目結構:

安裝
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: '韓國'
},
{
name: 'AnNi',
age: 22,
nationality: '俄羅斯'
}
]
}
export default state;
state沒啥好解釋的就一個對象,放你要用的狀態(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}號女友的名字是${item.name},年齡${item.age},來自${item.nationality}`
}).join(',')
return `一共有${girlfirend.length}個女友,${info},可怕的是他只是一名${getters.userJob}。`
}
}
export default getters;
getters接受兩個參數(shù),第一個是state,第二個是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嚴禁在mutations里面進行異步操作,嚴格模式報錯,難于調試
axios.get('/myServer').then(res => {
if (res.status === 200) {
state.firend = res.data.data.list
}
})
}
}
export default mutations;
mutations接受兩個參數(shù):state payload(調用時攜帶的參數(shù)),他是唯一可以修改state的地方,注意不可異步、不可調接口,嚴格模式會報錯
如圖:

actions.js
import axios from 'axios';
const actions = {
addGirlFirend ({ commit, state, getters }, payload) {
commit('addGirlFirend', payload);
},
getFirends (ctx) { //ctx是store下當前module對象
axios.get('/myServer').then(res => {
if (res.status === 200) {
ctx.commit('getFirend', res.data.data.list)
//直接在actions里面也可以修改state,但是不建議,創(chuàng)建store時用嚴格模式,會報錯,不符合vuex單向數(shù)據(jù)流的規(guī)范(只能在mutions里面修改state)
// ctx.state.firend = res.data.data.list
}
})
}
}
export default actions;
actions接受一個當前module的上下文對象(常用有commit),用來commit 提交mutations,主要用來請求后端數(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;
把各個組件集合起來暴露出模塊
再來看看store的實例化
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({
//在嚴格模式下,無論何時發(fā)生了狀態(tài)變更且不是由 mutation 函數(shù)引起的,將會拋出錯誤。這能保證所有的狀態(tài)變更都能被調試工具跟蹤到。
//*嚴格模式會深度監(jiān)測狀態(tài)樹來檢測不合規(guī)的狀態(tài)變更——請確保在發(fā)布環(huán)境下關閉嚴格模式,以避免性能損失。
strict: process.env.NODE_ENV !== 'production',//自動在生產(chǎn)環(huán)境下關閉嚴格模式
modules: {
moduleA,
moduleB
}
})
export default store
注意:一定要用Vue.use一下vuex,最好使用嚴格模式!
當然store里面還可以用命名空間和插件,一般項目用不上
掛載store
在項目主文件
main.js 實例化vue時,掛載
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
直接在實例里面看怎么快速使用store吧
helloWorld.vue
<template>
<div>
<Card style="width:550px">
<div slot="title">
<Icon type="ios-film-outline"></Icon>
個人信息
</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>
國籍:
<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)
// 上面兩個輔助函數(shù)方法的實質跟下面是一樣的,推薦 使用輔助函數(shù)
addAge () {
this.$store.commit('ageAdd', 2)
},
addGirlFirend1 () {
this.$store.dispatch('addGirlFirend', this.girlInfo)
}
}
}
先看一下初始UI吧

簡單解釋一下
主要的4個模塊,有對應的四個輔助函數(shù),用處是把狀態(tài) 和 操作映射到當前頁面
mapState和mapGetters,是狀態(tài)數(shù)據(jù),放在計算屬性;mapMutations和mapActions是操作函數(shù), 顯然放在方法里面;
注意帶的注釋;
直接看效果吧
調用mutations

調用actions

actions調接口


vuex的問題,解決方法點擊vuex刷新state就沒了
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Vue 2源碼解析HTMLParserOptions.start函數(shù)方法
這篇文章主要為大家介紹了Vue 2源碼解析HTMLParserOptions.start函數(shù)方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08
詳解vuex中action何時完成以及如何正確調用dispatch的思考
這篇文章主要介紹了詳解vuex中action何時完成以及如何正確調用dispatch的思考,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01
vue-cli是什么及創(chuàng)建vue-cli項目的方法
vue-cli是 vue 官方提供的、快速生成 vue 工程化項目的工具,支持創(chuàng)建vue2和vue3的項目,本文給大家詳細講解vue-cli是什么及創(chuàng)建vue-cli項目的方法,感興趣的朋友跟隨小編一起看看吧2023-04-04
vue3?setup中父組件通過Ref調用子組件的方法(實例代碼)
這篇文章主要介紹了vue3?setup中父組件通過Ref調用子組件的方法,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-08-08
proxy代理不生效以及vue?config.js不生效解決方法
在開發(fā)Vue項目過程中,使用了Proxy代理進行數(shù)據(jù)劫持,但是在實際運行過程中發(fā)現(xiàn)代理并沒有生效,也就是說數(shù)據(jù)并沒有被劫持,這篇文章主要給大家介紹了關于proxy代理不生效以及vue?config.js不生效解決方法的相關資料,需要的朋友可以參考下2023-11-11

