• [Vuex] Create a Vuex Store using TypeScript


    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

  • 相关阅读:
    继承与派生
    函数,迭代器,生成器
    面向对象
    函数
    模块与包
    python面试题(转自https://www.cnblogs.com/wupeiqi/p/9078770.html)
    python学习大纲目录(转自alex博客https://www.cnblogs.com/alex3714/)
    Mysql(基础篇)
    初识HTML和CSS2
    初识前端作业1
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10771689.html
Copyright © 2020-2023  润新知