vuex基本配置

目录

1.创建一个Vuex的store对象

2.在Vue组件中使用store


Vuex是一个Vue.js状态管理模式,它可以把数据存储到全局,并在不同组件之间共享这些数据。以下是Vuex的基本配置:

1.创建一个Vuex的store对象

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: { //存放全局状态
    count: 0
  },
  mutations: { //改变状态的方法
    increment(state) {
      state.count++
    },
    decrement(state) {
      state.count--
    }
  },
  actions: { //异步操作,提交mutations来改变状态
    incrementAsync(context) {
      setTimeout(() => {
        context.commit('increment')
      }, 1000)
    }
  },
  getters: { //计算状态属性
    doubledCount: state => {
      return state.count * 2
    }
  }
})

在store中,我们可以定义state、mutations、actions和getters,分别用来存放全局状态、改变状态的方法、异步操作和计算状态属性。

2.在Vue组件中使用store

<template>
  <div>
    <p>{{ count }}</p>
    <p>{{ doubledCount }}</p>
    <button @click="increment">+</button>
    <button @click="decrement">-</button>
    <button @click="incrementAsync">+ async</button>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex'

export default {
  computed: {
    ...mapState(['count']),
    ...mapGetters(['doubledCount'])
  },
  methods: {
    ...mapActions(['increment', 'decrement', 'incrementAsync'])
  }
}
</script>

在Vue组件中,我们可以通过mapState、mapGetters、mapActions来访问store中的状态、计算属性和方法。使用这些辅助函数可以更方便地访问store,并且可以省去一些重复的代码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
配置Vue 3和TypeScript的Vuex,你可以按照以下步骤进行操作: 1. 安装依赖: ```bash npm install vuex@next npm install --save-dev @types/vuex ``` 2. 创建一个`store`文件夹,并在其中创建一个`index.ts`文件。 3. 在`index.ts`中,引入VueVuex并创建一个新的`store`实例。以下是一个基本的示例: ```typescript import { createStore } from 'vuex'; import { InjectionKey } from 'vue'; // 定义 state、mutations、actions 和 getters // 创建一个注入键 export const key: InjectionKey<Store<State>> = Symbol(); // 创建 store 实例 export const store = createStore<State>({ state: { /* 初始化状态 */ }, mutations: { /* 定义修改状态的方法 */ }, actions: { /* 定义触发异步操作的方法 */ }, getters: { /* 定义获取状态的方法 */ } }); // 定义 RootState 类型 declare module '@vue/runtime-core' { interface ComponentCustomProperties { $store: typeof store; } } // 导出 store 实例 export function useStore() { return store; } ``` 4. 在你的主入口文件(通常是`main.ts`)中,使用`app.use()`方法安装Vuex插件,并将store实例传递给它。 ```typescript import { createApp } from 'vue'; import App from './App.vue'; import { store, key } from './store/index'; const app = createApp(App); app.use(store, key); app.mount('#app'); ``` 现在,你已经成功配置Vue 3和TypeScript的Vuex。你可以在组件中使用`$store`属性来访问Vuex的状态、操作和获取器。 希望对你有所帮助!如有任何问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XINGZI H.Z.X

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值