狀態(tài)管理: 簡單理解就是統(tǒng)一管理和維護各個vue組件的可變化狀態(tài)(你可以理解成 vue 組件里的某些 data)
Vuex是什么
Vuex是集中的應用程序架構為了Vue.js應用程序狀態(tài)管理。靈感來自 Flux 和 Redux ,但簡化的概念和實現(xiàn)是一個專門為 Vue.js 應用設計的狀態(tài)管理架構。
為什么要用vuex
隨著應用復雜度的增加,組件之間傳遞數(shù)據(jù)或組件的狀態(tài)就會越來越多,如果我們按照最基本的方式來進行通信,代碼就會變得十分混亂,特別在多人合作的時候。
此時vuex出現(xiàn)了,他就是幫助我們把公用的狀態(tài)全抽出來放在vuex的容器中,然后根據(jù)一定的規(guī)則來進行管理
Vuex的核心
Vuex.Store構造器
Vuex 中 Store 的模板化定義如下:
- state定義了應用狀態(tài)的數(shù)據(jù)結構,同樣可以在這里設置默認的初始狀態(tài)。
state:{
todoLists:[],
},
- getters就是從state中派生出狀態(tài),比如獲取state中todoLists的總數(shù)。類似vue中計算屬性(computed)
//Getters函數(shù) 接受 state 作為其第一個參數(shù)
getters:{
todoCount(state){
return state.todoLists.length;
}
},
- mutations是唯一允許更新應用狀態(tài)的地方。類似vue中的$on事件:每個 mutation 都有一個字符串的事件類型 (type)和 一個回調函數(shù) (handler)。
//和Getters函數(shù)一樣 接受 state 作為其第一個參數(shù)
mutations:{
//新増 TodoList item
ONADDTODO(state,item){
state.aTodos.push(item);
},
//刪除 TodoList item
ONDELTODO(state,index){
state.aTodos.splice(index,1);
},
//設置 錯誤提示信息
ONERROR(state,str){
state.massage=str;
}
},
- actions定義提交觸發(fā)更改信息的描述,在actions中可做任意異步操作,常見的例子有從服務端獲取數(shù)據(jù),在數(shù)據(jù)獲取完成后會調用store.commit()(類似vue中$emit)來調用更改 Store 中的狀態(tài)。可以在組件中使用dispatch來發(fā)出 Actions。
//Action 函數(shù)接受一個與 store 實例具有相同方法和屬性的 context 對象,
因此你可以調用 context.commit 提交一個 mutation,
或者通過 context.state 和 context.getters 來獲取 state 和 getters
actions:{
//提交 ONADDTODO
onAddTodo(context,item){
if(item.value!=""){
context.commit("ONADDTODO",item);
context.commit("ONERROR","");
}else{
context.commit("ONERROR","添加失敗")
}
},
//提交 ONDELTODO
//可利用 ES2015 的 [參數(shù)解構] 來簡化代碼
onDelTodo({commit},index){
//commit=context.commit
commit("ONDELTODO",index);
}
}
- modules對象允許將單一的 Store 拆分為多個 Store 的同時保存在單一的狀態(tài)樹中。隨著應用復雜度的增加,這種拆分能夠更好地組織代碼,更多細節(jié)參考這里。
Vuex輔助函數(shù)
Vuex.mapState(map: Array<string> | Object): Object
創(chuàng)建組件的計算屬性返回 Vuex store 中的狀態(tài)。Vuex.mapGetters(map: Array<string> | Object): Object
創(chuàng)建組件的計算屬性返回 getter 的返回值。Vuex.mapActions(map: Array<string> | Object): Object
創(chuàng)建組件方法分發(fā) action。Vuex.mapMutations(map: Array<string> | Object): Object
創(chuàng)建組件方法提交 mutation。
Vuex輔助函數(shù)具體用法參看:API文檔
TodoList示例
在理解了 Vuex 的基礎概念之后,我們會創(chuàng)建一個todolist來熟悉整個使用流程。
- 使用vue-cli工具創(chuàng)建項目目錄,并安裝vuex
vue init webpack-simple vue-vuex-todolist
npm install
npm install vuex --save
npm run dev //啟動項目
- src 目錄下創(chuàng)建名為 store 的目錄來存放狀態(tài)管理相關代碼,首先創(chuàng)建 index.js
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const store = new Vuex.Store({
state:{
massage:"",
aTodos:[{value:"默認默認",id:0}],
},
getters:{
nCounts(state){
return state.aTodos.length;
}
},
mutations:{
//新増 TodoList item
ONADDTODO(state,item){
state.aTodos.push(item);
},
//刪除 TodoList item
ONDELTODO(state,index){
state.aTodos.splice(index,1);
},
//設置 錯誤提示信息
ONERROR(state,str){
state.massage=str;
}
},
actions:{
//提交 ONADDTODO
onAddTodo(context,item){
if(item.value!=""){
context.commit("ONADDTODO",item);
context.commit("ONERROR","");
}else{
context.commit("ONERROR","添加失敗")
}
},
//提交 ONDELTODO
onDelTodo({commit},index){
commit("ONDELTODO",index);
}
},
modules:{}
});
export default store;
- main.js 文件中將該 Store 實例添加到構造的 Vue 實例中
import Vue from 'vue';
import App from './App.vue';
import store from './store';
new Vue({
el: '#app',
store,
render: h => h(App)
})
- src 目錄下創(chuàng)建名為 components的目錄來存放vue組件,并創(chuàng)建input.vue,list.vue文件
input.vue
<template>
<div class="form-group ">
<input type="text" class="form-control" placeholder="" v-model="value" />
<button type="buttom" class="btn btn-default" @click="addItem">Add Item</button>
</div>
</template>
<script>
export default{
data(){
return {
value:"",
id:0
}
},
methods:{
addItem(){
let item={value:this.value,id:++this.id};
this.value="";
this.$store.dispatch("onAddTodo",item);
}
}
}
</script>
<style lang="scss">
%box{display:-webkit-box;-webkit-box-pack:center;-webkit-box-align:center;}
.form-group{@extend %box;
.form-control{-webkit-box-flex:1;}
}
</style>
list.vue
<template>
<div class="todolist">
<ul class="list-group">
<li class="list-group-item" v-for="(item,index) in aTodos" >
<span>{{item.value}}</span>
<button class="btn btn-default" @click="delItem(index)">刪除</button>
</li>
</ul>
</div>
</template>
<script>
import {mapState} from "vuex";
export default{
data(){
return {}
},
methods:{
delItem(index){
this.$store.dispatch('onDelTodo',index);
}
},
computed:{
...mapState([
'aTodos'
])
}
}
</script>
<style lang="scss">
%box{display:-webkit-box;-webkit-box-pack:center;-webkit-box-align:center;}
.list-group-item{display: -webkit-box;-webkit-box-align:center;
span{
display: block;
-webkit-box-flex:1;
}
}
</style>
- 修改App.vue文件
<template>
<div id="app">
<h1>Vue.js Vue TodoList</h1>
<hr>
<todoInput />
<todoList />
<p>todoList 數(shù)量:{{todoCount}}</p>
<pre>{{$store.state}}</pre>
</div>
</template>
<script>
import todoInput from './components/input.vue';
import todoList from './components/list.vue';
import {mapGetters} from "vuex";
export default {
name: 'app',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},
computed:{
...mapGetters({
todoCount:"nCounts"
})
},
components:{
todoInput,
todoList
}
}
</script>
<style lang="scss">
%box{display:-webkit-box;-webkit-box-pack:center;-webkit-box-align:center;}
#app{width:400px;margin:0 auto;}
h1{text-align:center;}
</style>
- index.html添加bootstrap.css
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>vue-vuex-demo</title>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div id="app"></div>
<script src="/dist/build.js"></script>
</body>
</html>
最后運行查看效果
最后再附上:vuex入門demo無需依賴任何打包工具http://runjs.cn/code/7enrwlef