vue3+ts vuex存储问题

发布时间:2023年12月26日
import { createStore } from "vuex"

import persistedstate from "vuex-persistedstate";
import  user from "./modules/user"

export default createStore({
    state: {
        num: 10,
        sum:10,
        str:"这是store数据"
    },
    getters: {
        total(state) {
            return  state.num+state.sum
        }
    },
    mutations: {
        changeNum(state,val) {
            state.num = val;
        }
    },
    actions: {
        changeBtn() {
            alert(1)
        }
    },
    modules: {
        user
    },
    // 持久化存储
    plugins: [persistedstate({
        key: "vuexStr",
        paths:['user']
    })]
})

./modules/user

export default {
    state: {
        userInfo: {
            name: '',
            age: '',
            sex:''
        }
    },
    mutations: {
        changeInfo(state:any) {
            state.userInfo = {
                name: '123',
                age: "12",
                sex:'男'
            }
        }
    }
}

页面使用:

<template>
  <p>num:{{ num }}</p>
  <p>total:{{ total }}</p>
  <button @click="btnCli">修改值</button>

  <p>---------------------</p>
  <p>---------------------</p>
  <p>---------------------</p>
  <p>用户名:{{ userInfo.name }}</p>
  <p>性别:{{ userInfo.sex }}</p>
  <p>年龄:{{ userInfo.age }}</p>
  <button @click="updateUser">修改用户信息</button>
</template>

<script setup lang="ts">
import { computed } from "vue";
import { useStore } from "vuex";
let store = useStore();
let num = computed(() => store.state.num);
let total = computed(() => store.getters.total);

// userinfo

let userInfo = computed(() => store.state.user.userInfo);
console.log(store);
const btnCli = () => {
  // store.commit("changeNum", 500);
  store.dispatch("changeBtn");
};

const updateUser = () => {
  store.commit("changeInfo");
};
</script>

<style></style>

效果图一:

在这里插入图片描述

文章来源:https://blog.csdn.net/weixin_45932157/article/details/135211448
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。