引入
npm install vuex --save
在main.js引入import Vuex from 'vuex'
安装好了之后会在模块包里
store就是vuex的注入方式。
状态管理模式
每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。
1,Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
2,你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。
使用vuex的过程:
Vuex 通过 store 选项,提供了一种机制将状态从根组件“注入”到每一个子组件中(需调用 Vue.use(Vuex)):
在main.js中注册
在main.js中:
new Vue({
el: '#app',
router,
store,
components: {App},
template: '<App/>'
}
在组件中使用时用$store.commit
单一状态树:
state
计算属性: store.state.函数名
用 . 来一层层剥开
通过在根实例中注册 store 选项,该 store 实例会注入到根组件下的所有子组件中,且子组件能通过 this.$store 访问到。
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count
}
}
}
Mutation
更改store中的状态。
每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。
你不能直接调用一个 mutation handler。这个选项更像是事件注册:“当触发一个类型为 increment 的 mutation 时,调用此函数。”要唤醒一个 mutation handler,你需要以相应的 type 调用 store.commit 方法:
store.commit('increment')
在vuex/store.js中写入vuex:
import Vue from "vue";
import Vuex from "vuex";
// localStorage
import creatPedrsistedstate from "vuex-persistedstate"
Vue.use(Vuex);
export default new Vuex.Store({
plugins: [
creatPedrsistedstate()
],
state: {
user: {
uid: "",
uname: "",
name: "",
pwd: ""
},
cur_route: "",
token: "",
major: ""
},
mutations: {
// 记录token
record_token(state,val) {
state.token = val;
},
// 记录一级课程
record_major(state,val) {
state.major = val;
},
// 记录登陆落地页
record_cul_route(state,val) {
state.cul_route = val;
},
// 用户登陆
login(state,val) {
state.user = val;
},
// 退出登录
exit_login(state) {
// 全置为空
state.user.uid = state.user.uname = state.user.name = state.user.pwd = state.cur_route = state.token = state.major = "";
},
// 修改用户名
update_uname(state,uname) {
state.user.uname = uname;
},
}
})