[Vuex] Create a Vuex Store using TypeScript

本文详细介绍了如何利用TypeScript与Vuex在Vue应用中创建并使用集中式状态管理。通过定义清晰的State接口,创建store,并在组件中使用@State装饰器来访问状态,展示了状态管理的最佳实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A Vuex store centralizes the state of your app, making it easy to reason about your state flow.

In this lesson we’ll see how we can create a Vuex store using TypeScript and use it on you class-based component by using the @State decorator from Vuex Class

 

Install:

npm i vuex vuex-class --save

 

Create store folder and index.ts, todos.ts file:

//store/index.ts

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

import todos from './todos';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    ...todos,
  },
  mutations: {

  },
  actions: {

  },
});


// store/todos.ts
import {State} from '../types';

const state: State = {
    todos: [
        {text: 'Buy milk'},
    ],
};

export default state;

 

Define the State interface:

// types.ts

export interface Todo {
    text: string;
}

export interface State {
    todos: Todo[];
}

 

Using Store in main.ts:

import './hooks';

import Vue from 'vue';
import App from './App.vue';
import router from '@/router';
import store from '@/store/index';
import '@/registerServiceWorker';
Vue.config.productionTip = false;


new Vue({
  router,
  store,
  render: (h) => h(App),
}).$mount('#app');

 

Create a Todos.vue component:

<template>
    <ul>
      <li v-for="todo in todos">{{ todo.text }}</li>
    </ul>
</template>

<script lang="ts">
import {Component, Vue} from 'vue-property-decorator';
import {State} from 'vuex-class';
import {Todo} from '../types';

@Component({
})
export default class Todos extends Vue {
    @State todos: Todo[]
}
</script>

 

See the commit

转载于:https://www.cnblogs.com/Answer1215/p/10771689.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值