vue3 使用vuex

import  {createStore} from 'vuex';
import moduleA from './moduleA/index.js'
export default  createStore({
 state:{
    a:1
 },
 getters:{
    comA(state){
        return state.a *2
    }
 },
 mutations:{
   syncChangeA(state,payload){
      state.a += payload
   }
 },
 actions:{
    AsyncChangeA({commit},payload){
       setTimeout(() => {
        commit('syncChangeA',payload)
       }, 1000);
    }
 },
 modules:{
    moduleA
 }
})
<template>
  <div>
    <h1>iii</h1>
    <h1>{{ a }}</h1>
    <h1>{{ comA }}</h1>
    <h1>{{ comaa }}</h1>
    <h1>{{ comModuleA }}---</h1>
    <button @click="handleSyncChangeA">改变a同步</button>
    <button @click="handleAsyncChangeA">改变a异步</button>
    <button @click="handleInstance">操作实例</button>
    <h1>{{ aa }}</h1>
    <h1>{{ bb }}</h1>
    <button @click="syncChangeModule">同步改变模块</button>
  </div>
</template>
<script lang="ts" setup>

import {ref, toRefs, reactive, getCurrentInstance, onMounted, computed } from "vue";
import { useStore, mapState ,mapGetters} from "vuex";
let { proxy }: any = getCurrentInstance();


let aa = computed(() => {
  return 999;
});
let bb = computed(() => {
  return 888;
});

let comaa = computed(() => {
  return instanceStore.getters.comA;
});

//通过实例点出来
let handleInstance = () => {
  proxy.$store.commit("syncChangeA", 2);
};
//通过解构赋值
const instanceStore = useStore();



// let {} = toRefs(instanceStore.getters)
let comModuleA= instanceStore.getters['moduleA/comModuleA'];

// 模块内的方法
let syncChangeModule = ()=>{
    instanceStore.commit('moduleA/moduleSync',9)
}
let { a } = toRefs(instanceStore.state);
let { comA ,} = toRefs(reactive(instanceStore.getters));//toRefs接收一个响应式对象 不加reactive 警告 receive a plain one
let handleSyncChangeA = () => {
  instanceStore.commit("syncChangeA", 1);
};
let handleAsyncChangeA = () => {
  instanceStore.dispatch("AsyncChangeA", 1);
};
</script>
<style scoped></style>
export default {
  namespaced: true,
  state: {
    moduleA: 11,
  },
  getters: {
    comModuleA(state) {
      return state.moduleA * 2;
    },
  },
  mutations:{
    moduleSync(state,payload){
         state.moduleA +=payload;
         
    }
  }
};

vuexStore.commit('moduleA/setCount', 2)
vuexStore.dispatch('moduleA/getuser')

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值