【无标题】uni-app中使用vuex

标题 模拟用户登录把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>

发送请求前

请添加图片描述

发送请求后

请添加图片描述

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值