vue通过vuex或provide异步数据设置为全局变量

store 

// store.js

import Vue from 'vue';

import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({

  state: {

    userInfoSession: null,

    userInfoState: null

  },

  mutations: {

    setUserInfoState(state, userInfo) {

      state.userInfoState = userInfo;

    },

    setUserInfoSession(state, userInfo) {

      state.userInfoSession = userInfo;

    }

  },

  actions: {

    fetchUserInfoState({ commit }) {

      return new Promise((resolve) => {

        setTimeout(() => {

          const data = { userId: 10081, name: '张三' };

          commit('setUserInfoState', data);

          resolve(data);

        }, 1000);

      });

    },

    fetchUserInfoSession({commit}) {

      return new Promise((resolve) => {

        setTimeout(() => {

          const data = { userId: 10082, name: '张三' };

          commit('setUserInfoSession', data);

          //provide需要持久化一下

          sessionStorage.setItem('userInfo', JSON.stringify(data));

          resolve(data);

        }, 1000);

      });

    }

  },

  getters: {

    userInfo: state => state.userInfo

  },

});

app

<!--

 * @Author: mxuan

 * @LastEditors: mxuan

 * @LastEditTime: 2024-08-29 22:49:07

-->

<template>

  <div id="app">

    <router-view />

  </div>

</template>

<script>

export default {

  data(){

    return {

      userInfo: null

    }

  },

provide(){

  return{

     sessionUser:  () =>this.userInfo ?.userId

  }

},

  async created () {

    //分别调用state和session的 action

  this.userInfo= await  this.$store.dispatch('fetchUserInfoSession')

  this.$store.dispatch('fetchUserInfoState')

  },

  methods: {

   

  }

}

</script>

<style>

#app {

  font-family: Avenir, Helvetica, Arial, sans-serif;

  -webkit-font-smoothing: antialiased;

  -moz-osx-font-smoothing: grayscale;

  text-align: center;

  color: #2c3e50;

}

nav {

  padding: 30px;

}

nav a {

  font-weight: bold;

  color: #2c3e50;

}

nav a.router-link-exact-active {

  color: #42b983;

}

</style>

home组件  需要使用数据的组件

<template>

  <div class="home">

    <img alt="Vue logo"

         src="../assets/logo.png">

    <div>

      <button @click="aaa">清空存储</button>

      <p>用户ID: {{ userInfoState?.userId }}</p>

      <p>用户名: {{ userInfoState?.name }}</p>

    </div>

    <HelloWorld msg="欢迎来到你的 Vue.js 应用" />

  </div>

</template>

<script>

import HelloWorld from '@/components/HelloWorld.vue';

import { mapState } from 'vuex';

export default {

  inject: ['sessionUser'],

  computed: {

    ...mapState(['userInfoState']),

    compUser () { return this.sessionUser() }

  },

  data () {

    return {

      userIdSession: null,

      userIdState: null

    }

  },

  watch: {

    userInfoState: {

      handler (newVal) {

        console.log(newVal.userId,'store的watch')

        this.userIdState = newVal.userId

        this.refershDataState()

      }

    },

    compUser: {

      handler (newVal) {

        console.log(this.compUser, 'seesion的watch')

        this.userIdSession = newVal

        this.refershDataSession()

      },

    }

  },

  methods: {

    aaa () {

      sessionStorage.clear()

    },

    refershDataSession () {

      setTimeout(() => {

        console.log(this.userIdSession, 'Session的ajax')

      }, 2000)

    },

    refershDataState () {

      setTimeout(() => {

        console.log(this.userIdState, 'state的ajax')

      }, 2000)

    },

  },

  name: 'HomeView',

  components: {

    HelloWorld

  }

}

</script>

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值