vue中如何获取或者改变vuex中的值

vue中如何获取或者改变vuex中的值

store–>index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
	isLogin:localStorage.getItem("isLogin")?localStorage.getItem("isLogin"):false,//判断是否登录
  },
  mutations: {
	//判断是否登录
	setLogin(state,payload){
		state.isLogin=payload
		localStorage.setItem("isLogin",state.isLogin)
	},
	//退出登录
	logout(state){
		console.log("[退出登录]",state)
		state.isLogin=false
		localStorage.clear();//清除本地缓存
	}
  },
  actions: {
	getLogin(context,payload){
		context.commit("setLogin",payload)
	}
  },
  modules: {
	
  }
})

在页面中使用或者修改vuex中的值

<script>
	import { mapState, mapActions,mapMutations } from "vuex"
	export default {
		name:"index",
		data() {
			return {
				
			}
		},
		computed:{
			...mapState({
				isLogin:state=>state.isLogin
			}),//等同于==>...mapState(['isLogin']);映射 this.isLogin 为 this.$store.state.isLogin
		},
		mounted(){
			
			console.log("[mapState]",this.isLogin)
			
			this.$store.state.isLogin;//等同于==》this.isLogin
			
			this.$store.dispatch("getLogin",true);//等同于==》this.getLogin(true);dispatch触发actions里的方法,Action 提交的是 mutation,而不是直接变更状态,Action 可以包含任意异步操作
			
			this.$store.commit("logout");//等同于==》this.logout();commit触发mutations里的方法,更改 Vuex 的 store 中的状态的唯一方法是提交 mutation
			
			console.log(this.$store.state.isLogin)
			console.log(localStorage.getItem("isLogin"))
		},
		methods:{
			...mapMutations(["logout"]),// 将 `this.logout()` 映射为 `this.$store.commit('logout')`
			...mapActions(["getLogin"]),// 将 `this.getLogin()` 映射为 `this.$store.dispatch('getLogin')`
		}
	}
</script>
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值