Vue3中Vuex的基本使用

src/store/uuidState.js

const uuidState = {
  namespaced: true,
  state: {
    uuid: "",
    state_tag: "",
  },
  // 要想改变state中的数据必须使用mutations的方法
  mutations: {
    changeUuid(state, value) {
      state.uuid = value;
    },
    changeTag(state, value) {
      state.state_tag = value;
    },
  },
  // 异步的方法
  actions: {
    CHANGE_TAG(context, value) {
      setTimeout(() => {}, 2000);
      context.commit("changeTag", value);
    },
  },
  // 类似计算属性
  getters: {
    uuidToUpper(state) {
      return state.uuid.toUpperCase();
    },
  },
};

// export default uuidState;
export default { uuidState };

src/store/index.js

import { createStore } from "vuex";
import uuidState from "./uuidState";
export default createStore({
  state: {
    code: "this is a code",
  },
  getters: {
    CODE(state) {
      return state.code.toUpperCase();
    },
  },
  mutations: {},
  actions: {},
  modules: {
    // uuidState,
    uuidState: uuidState.uuidState,
  },
});

src/views/Vue3Vuex.vue

<template>
    <div>Vue3------Vuex复习</div>
    <div>使用模块中的state:{{ $store.state.uuidState.uuid }}</div>
    <div>使用模块中的getters:{{ $store.getters['uuidState/uuidToUpper'] }}</div>
    <div>使用非模块的state:{{ $store.state.code }}</div>
    <div>使用非模块的getters:{{ $store.getters.CODE }}</div>
</template>

<script setup>
import { nanoid } from 'nanoid'
import { useStore } from 'vuex';
const store = useStore()
// 使用mutations修改state中的的值
const saveuuid = () => {
    const uuid = nanoid()
    store.commit('uuidState/changeUuid', uuid)
}
// 获取state中的值
const getuuid = () => {
    return store.state.uuidState.uuid
}
// 使用actions异步修改state的值
const setStateTag = () => {
    store.dispatch('uuidState/CHANGE_TAG', '-----actions-----')
}
// 使用getters加工state的数据
const getUuidUpper = () => {
    return store.getters['uuidState/uuidToUpper']
}
// 初始化
const init = () => {
    saveuuid()
    setStateTag()
    // console.log('store', store);
    console.log('uuid', store.state.uuidState.uuid);
    console.log('state_tag', store.state.uuidState.state_tag);
    console.log('getter', store.getters['uuidState/uuidToUpper']);
}
init()
</script>

<style lang="scss" scoped>
</style>

结果展示:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值