对于新手来说,一开始接触vuex时候只听说它很强大,很好用,各种nb操作,一旦尝试去了解它的时候便显得力不从心。本人也是如此,一开始接触的时候通过看文档, 看视频,最后还是把它搁一边去。一段时间之后回来再琢磨的时候,便有了新的认识和理解。
首先,如果你想真正掌握vuex,那么就的弄清楚这几个问题:
1.什么是vuex?
2.在什么情况下要用到vuex(也就是vuex能够解决什么样的问题),什么情况下适合用vuex?
那么先来看看这两个问题:
什么是vuex?官网说:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。 按个人通俗理解来说就是:vuex就是用来管理各个组件之间的一些状态,可以理解为这些状态就是公共(共享)部分。此时任何组件都能从中获取状态或者触发一些行为事件。
什么情况下用到vuex?官网说:如果您不打算开发大型单页应用,使用 Vuex 可能是繁琐冗余的。确实是如此——如果您的应用够简单,您最好不要使用 Vuex。一个简单的 global event bus 就足够您所需了。但是,如果您需要构建是一个中大型单页应用,您很可能会考虑如何更好地在组件外部管理状态,Vuex 将会成为自然而然的选择。
好,那么现在我就当你是开发一个比较大型的项目,在那些地方会用到vuex呢? 随着应用的复杂度增加,组件之间传递数据或组件的状态会越来越多,举个例子:当A组件进入B组件(A页面进入B页面)的时候,常常需要带一些参数过去,那么此时你可能会选择放在url后面当做参数传递过去,如果你不想轻易暴露参数,你有可能先存到session中或者localstorage中,然后进入到第二个页面的时候再取出来。不错,这确实是一种解决方法,而且用的不少。但这不是一个好的方法,这时候,你就需要vuex来帮助你了。另外,当你基本了解vuex的一些皮毛之后,你会发现vuex管理是基于模块化的思想,那么这就对项目后期管理维护很友好了。
so,现在你就得来深入认识一下vuex的核心概念了。下面是个人理解的概念,首先在此之前建议最好先把官方文档Vuex2.0概念过一遍。
Vuex 中 Store 的模板化定义如下:
1 、state 定义了应用的数据结构,也就是vuex中放初始化数据(状态)的地方。相当于组件中的data用来放数据。
state:{
todoLists:[],
},
2、getters 就是从state中派生出状态,比如获取state中todoLists的总数。其实就是相当于vue中的计算属性computed,只不过getters是放在vuex中的。
//Getters函数 接受 state 作为其第一个参数
getters:{
todoCount(state){
return state.todoLists.length;
}
},
3、mutations 是唯一允许更新应用状态的地方。类似vue中的$on事件:每个 mutation 都有一个字符串的事件类型 (type)和 一个回调函数 (handler)。注意:mutations都必须是同步函数
//和Getters函数一样 接受 state 作为其第一个参数
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;
}
},
4、actions 定义提交触发更改信息的描述,在actions中可做任意异步操作,常见的例子有从服务端获取数据,在数据获取完成后会调用store.commit()(类似vue中$emit)来调用更改 Store 中的状态。可以在组件中使用dispatch来发出 Actions。
//Action 函数接受一个与 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 的 [参数解构] 来简化代码
onDelTodo({commit},index){
//commit=context.commit
commit("ONDELTODO",index);
}
}
Vuex辅助函数
-
Vuex.mapState(map: Array<string> | Object): Object
创建组件的计算属性返回 Vuex store 中的状态。 -
Vuex.mapGetters(map: Array<string> | Object): Object
创建组件的计算属性返回 getter 的返回值。 -
Vuex.mapActions(map: Array<string> | Object): Object
创建组件方法分发 action。 -
Vuex.mapMutations(map: Array<string> | Object): Object
创建组件方法提交 mutation。
Vuex辅助函数具体用法参看:API文档
TodoList示例
在理解了 Vuex 的基础概念之后,我们会创建一个todolist来熟悉整个使用流程。
- 使用vue-cli工具创建项目目录,并安装vuex
vue init webpack-simple vue-vuex-todolist
npm install
npm install vuex --save
npm run dev //启动项目
- src 目录下创建名为 store 的目录来存放状态管理相关代码,首先创建 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 目录下创建名为 components的目录来存放vue组件,并创建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 数量:{{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" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div id="app"></div>
<script src="/dist/build.js"></script>
</body>
</html>
以上demo是参考网友的,写的不错,可以借鉴帮助理解。