vuex是什么虎锚?
先引用官方原話:Vuex 是一個專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲管理應(yīng)用的所有組件的狀態(tài),并以相應(yīng)的規(guī)則保證狀態(tài)以一種可預(yù)測的方式發(fā)生變化。Vuex 也集成到 Vue 的官方調(diào)試工具 devtools extension,提供了諸如零配置的 time-travel 調(diào)試思劳、狀態(tài)快照導(dǎo)入導(dǎo)出等高級調(diào)試功能。
通俗來說妨猩,vuex就是管理全局的變量潜叛,可以在任何組件中調(diào)用和修改數(shù)據(jù)。父子組件通信時壶硅,我們通常會采用 props + emit 這種方式威兜。但當(dāng)通信雙方不是父子組件甚至壓根不存在相關(guān)聯(lián)系,或者一個狀態(tài)需要共享給多個組件時庐椒,就會非常麻煩椒舵,數(shù)據(jù)也會相當(dāng)難維護,這對我們開發(fā)來講就很不友好约谈。vuex 這個時候就很實用笔宿,不過在使用vuex之后也帶來了更多的概念和框架,需慎重棱诱!
vuex有幾個模塊泼橘?
vuex一共分為五個模塊 State、gertters迈勋、mutations炬灭、actions、mudules(模塊化)
他們之間的關(guān)系圖:
State :單一狀態(tài)樹靡菇,類似vue中的data重归,存放數(shù)據(jù)的。
getters:計算屬性厦凤,類似于computed一樣鼻吮,當(dāng)它的依賴值發(fā)生變化的時候,它就會重新計算賦值泳唠,并有緩存狈网。
mutations:操作state數(shù)據(jù)(同步)
actions:action 提交的是 mutation宙搬,而不是直接變更狀態(tài)笨腥。Action 可以包含任意異步操作。
mudules:模塊化狀態(tài)管理
代碼實現(xiàn)
store 下的index.js
import Vue from 'vue'
import Vuex from 'vuex'
import modules from './modules_export'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
modules
}
})
store下的modules_export.js
const files = require.context('./modules', false, /\.js$/)
const modules = {}
files.keys().forEach(key => {
modules[key.replace(/(\.\/|\.js)/g, '')] = files(key).default
})
//console.log(modules);
export default {
namespaced: true,
modules
}
store下的 mudules文件下的index.js
//組件通過 this.$store.dispatch(''勇垛,data) 對actions 的方法脖母,然后用commit對mutations操作
export default {
namespaced: true,
state: {
//存放鍵值所在的管理狀態(tài)
name: 123
},
getters: {
//使用this.$store.getters.g_name 可以獲取state中的name值
g_name: state => {
return state.name
}
},
actions: {
a_edit1(context, payload) {
return new Promise((resolve) => {
setTimeout(() => {
context.commit('m_edit1', payload)
resolve()
}, 2000)
})
}
},
mutations: {
m_edit1(state, data) {
state.name += data
}
},
}
main.js中的配置
import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
store,//將vuex掛載在vue實例
render: h => h(App),
}).$mount('#app')
組件中使用vuex
<template>
<div id="app">
<h1>{{g_name}}</h1>
<button style="margin:10px" @click="add1">加1</button>
</div>
</template>
<script>
import { mapGetters,mapActions } from "vuex"; //儲存數(shù)據(jù)
export default {
name: 'App',
data(){
return{
}
},
computed: {
...mapGetters("modules/index", ["g_name"])
},
methods: {
...mapActions("modules/index",['a_edit1']),
add1(){
this.$store.dispatch('modules/index/a_edit1',1);
console.log(this.g_name)
},
},
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
以上是vuex模塊化基礎(chǔ)使用