状态管理保存在storeindex.js中,简单说明如下
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ //存放状态 state: { //单个值 Name: '', age: 0, //对象 token: { accessToken: '', encryptedAccessToken: '', expireInSeconds: 0, userId: 0 } }, //state成员操作,必须通过mutations操作state mutations: { //state是当前VueX对象中的state //name是该方法在被调用时传递参数使用的 setName(state, name) { state.name = name }, //无参设置值 setAge(state) { state.age = 18 }, setToken(state, token) { state.token = token }, }, //异步操作 actions: {}, //模块化状态管理 modules: {}, //加工state成员给外界 getters: {} })
页面使用
<script> export default { data() { return { token: { accessToken: '', encryptedAccessToken: '', expireInSeconds: 0, userId: 0 } } }, methods: { btnDemo() { this.$store.commit('setAge'); //无参调用 this.$store.commit('setName','xiaoming') //有参赋值 this.$store.commit('setToken',this.token) //对象赋值 } } } </script>