iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >vue获取或者改变vuex中的值方式
  • 500
分享到

vue获取或者改变vuex中的值方式

2024-04-02 19:04:59 500人浏览 泡泡鱼
摘要

目录Vue获取或改变vuex的值store–>index.js在页面中使用或者修改vuex中的值监听vuex值变化实时改变问题如图思路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>

监听vuex值变化实时改变

问题如图

头部是一个组件,想在这个页面修改用户名点击确认修改后,头部名称跟到变化。

思路

用户名在登录成功过后,存在vuex里面并且保存在本地(防止刷新消失)

this.$store.commit('set_userName',res.data.data.username)

vuex中state.js :

userName:localStorage.getItem('userName') ? localStorage.getItem('userName') : '',

mutations.js

set_mobile(state,mobile){
    state.mobile=mobile
    localStorage.setItem('mobile', mobile);
  },

要取用户名就用

this.$store.state.userName;

要存用户名就用

this.$store.commit('set_userName',this.newName)

好!!重要的来了,就是在头部组件里面写监听事件,监听用户名改变时,随着变化

watch:{
      '$store.state.userName':function(){ //监听vuex中userName变化而改变header里面的值
        this.userName=this.$store.state.userName;
      }
    },

这样就可以实现在其他页面改变用户名达到实时变化

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: vue获取或者改变vuex中的值方式

本文链接: https://www.lsjlt.com/news/166688.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作