标题 模拟用户登录把token存到vuex里
(注:只是模拟,真实场景下token一般存在本地)
uni-app已经内置了vuex
1、在项目的根目录下,创建一个名为store的文件夹然后在该文件夹下创建一个index.js的js文件
2.index.js文件下定义公共的数据以及方法函数,并且把它导出
import Vue from "vue"
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count:1,
testArr: ["11", "22", "33"],
token:null
},
mutations: {
settoken(state,token){
state.token = token
console.log(token)
}
},
actions: {
getToken({commit}){
//创建一个请求
uni.request({
url:"{登录的接口}",
method:"POST",
//账号,密码
data:{"username":"admin","password":"admin123"},
success(res) {
const {code,msg,token} = res.data
//接口调用成功后 使用commit调用mutations里的函数并把token传过去
commit("settoken",token)
}
})
}
},
getters: {
count(state, getters) {
return state.count
},
testArr(state, getters) {
return state.testArr
},
}
})
export default store
3.main.js挂载vuex
import App from './App'
import Vue from 'vue'
import uView from "uview-ui";
Vue.use(uView);
//引入vuex 并且挂载到vue实例上
import store from "./store/index.js"
Vue.prototype.$store = store
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
3.首页代码
index.vue
<template>
<view class="content">
<view class="login">
首页
</view>
<view class="">
<button type="default" @click="getTOken">点击获取token</button>
</view>
<view class="" style="margin-top: 300rpx;">
这是公共数据:
<!-- <text>{{count}}</text> -->
<text>token: {{token}}</text>
<view class="">
</view>
<text>count: {{count}}</text>
<view class="">
</view>
<view v-for="(item,index) in testArr" :key="index">{{item}}</view>
</view>
</view>
</template>
<script>
import {
mapState,
mapActions,
mapMutations
} from "vuex";
export default {
data() {
return {
}
},
onLoad() {
},
methods: {
//把mapActions的方法放到methods里
...mapActions(["getToken"]),
//调用getToken获取token
getTOken() {
this.getToken()
},
},
//通过计算属性可以读取并实时监听状态的变化
computed: mapState({
count: state => state.count,
testArr: state => state.testArr,
token: state => state.token
})
}
</script>
<style scoped lang="scss">
</style>
发送请求前
发送请求后