欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue獲取或者改變vuex中的值方式

 更新時(shí)間:2022年09月02日 14:27:34   作者:miao_zz  
這篇文章主要介紹了vue獲取或者改變vuex中的值方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

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觸發(fā)actions里的方法,Action 提交的是 mutation,而不是直接變更狀態(tài),Action 可以包含任意異步操作
			
			this.$store.commit("logout");//等同于==》this.logout();commit觸發(fā)mutations里的方法,更改 Vuex 的 store 中的狀態(tài)的唯一方法是提交 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>

監(jiān)聽vuex值變化實(shí)時(shí)改變

問題如圖

頭部是一個(gè)組件,想在這個(gè)頁面修改用戶名點(diǎn)擊確認(rèn)修改后,頭部名稱跟到變化。

思路

用戶名在登錄成功過后,存在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)

好??!重要的來了,就是在頭部組件里面寫監(jiān)聽事件,監(jiān)聽用戶名改變時(shí),隨著變化

watch:{
      '$store.state.userName':function(){ //監(jiān)聽vuex中userName變化而改變header里面的值
        this.userName=this.$store.state.userName;
      }
    },

這樣就可以實(shí)現(xiàn)在其他頁面改變用戶名達(dá)到實(shí)時(shí)變化

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論