首先展示一下我的目录结构:

第一步:创建store目录,并且在store目录下面创建index.js
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)
const store = new Vuex.Store({
state: {// 用来缓存数据
name: 'jack',
isLogin: false, //判断是否已登录
},
mutations: {
// 改变isLogin的值
setLogin(state, payload) {
state.isLogin = payload;
}
}
})
export default store
第二步:在main.js里面引入:
import store from './store/index.js'
Vue.prototype.$store = store
import Vue from 'vue'
import App from './App'
##############看这里##########
// 手动引入 在index.js 上的vuex 代码
import store from './store/index.js'
Vue.prototype.$store = store
#############################
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
第三步:创建页面:pages/login/login.vue 并且在page.json里面配置这个页面。
{
"pages": [ //pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocation/pages
{
"path": "pages/login/login",
"style": {
"navigationBarTitleText": "uni-app"
}
}
],
"globalStyle": {
"navigationBarTextStyle": "black",
"navigationBarTitleText": "uni-app",
"navigationBarBackgroundColor": "#F8F8F8",
"backgroundColor": "#F8F8F8"
}
}
<template>
<view class="login">
<view>
登录状态: {{isLogin}}
</view>
<button type="default" @click="login">登录</button>
<button type="default" @click="logout">注销</button>
<navigator url="../index/index">首页</navigator>
</view>
</template>
<script>
import {mapState} from 'vuex'
export default {
computed: {
...mapState(['name','isLogin'])
},
methods: {
// 登录
login() {
this.$store.commit('setLogin', true);
},
// 登出 注销
logout() {
this.$store.commit('setLogin', false);
}
}
}
</script>
<style>
</style>
最后运行:访问login页面:

总结:
- vuex本事是缓存,适用于将首次加载,之后不用重新加载的接口,将接口数据缓存在这里,比如登陆的状态数据,真实的登陆肯定不是这样;
- index.js 当中创建store(new Vuex.Store),在store里面创建state变量,修改变量需要在mutations里面创建函数,setXXX 用来修改state里面的属性;
- 别忘了在main.js里面导入注册的vuex(store/index.js)
- 为了在index.vue里面能使用{{}}双括号来访问name 和 isLogin 属性,我们需要在computed添加 ...mapState(['name','isLogin']) 这句话的意思是将全局注册的state展开得到name和isLogin
- this.$store.commit('setLogin', true); 因为我们已经将Vuex注册到了main.js 所以我们可以通过这样的方式调用setLogin来设置isLogin