目录
1.概述
版本3.1.1;vuex是专门用来管理vue.js应用程序中状态的一个插件。他的作用是将应用中的所有状态都放在一起,集中式来管理。需要声明的是,这里所说的状态指的是vue组件中data里面的属性,可以做组件间的数据共享;
2.官方文档
3.目录结构
Vuex 并不限制你的代码结构。但是,它规定了一些需要遵守的规则:
-
应用层级的状态应该集中到单个 store 对象中。
-
提交 mutation 是更改状态的唯一方法,并且这个过程是同步的。
-
异步逻辑都应该封装到 action 里面。
只要你遵守以上规则,如何组织代码随你便。如果你的 store 文件太大,只需将 action、mutation 和 getter 分割到单独的文件。
├── index.html
├── main.js
├── api
│ └── ... # 抽取出API请求
├── components
│ ├── App.vue
│ └── ...
└── store
├── index.js # 我们组装模块并导出 store 的地方
├── actions.js # 根级别的 action
├── mutations.js # 根级别的 mutation
└── modules
├── cart.js # 购物车模块
└── products.js # 产品模块
4.加载应用
4.1项目目录
4.2index.js
import Vue from 'vue';
import Vuex from 'vuex';
import mutations from './mutations';
import actions from './actions';
Vue.use(Vuex);
const state ={
username: '',//登录用户名
cartCount: 0,//购物车商品数量
}
export default new Vuex.Store({
state,
mutations,
actions
})
4.3actions.js
export default {
}
4.4mutations.js
/**
* 商城vuex - mutations
*/
export default {
}
4.5main.js
import Vue from 'vue'
import store from "./store";
new Vue({
store: store,
render: h => h(App),
}).$mount('#app');
4.6查看效果
5.使用示例
5.1保存
this.$store.dispatch('saveUserName',res.username);
5.2actions.js
export default {
saveUserName(context,username){
context.commit('saveUserName',username);
}
}
5.3mutations.js
/**
* 商城vuex - mutations
*/
export default {
saveUserName(state,username){
state.username=username;
}
}
5.4获取
export default {
name: "nav-header",//name值,每一个组件都需要一个name值,最终加载组件的时候会用到
data() {
return {
poneList: [],
username: this.$store.state.username
}
}}
<a href="javascript:;" v-if="username">{{username}}</a>
<a href="javascript:;" @click="login" v-if="!username">登录</a>