zoukankan      html  css  js  c++  java
  • [Vuex] Lazy Load a Vuex Module at Runtime using TypeScript

    Sometimes we need to create modules at runtime, for example depending on a condition. We could even want to lazy load that module by using Webpack’s code splitting feature.

    For example, in current appliation, we are loading login and todos modules at the same time, now what we want is lazy load login module:

    import Vue from 'vue';
    import Vuex from 'vuex';
    
    import {todos} from './todos';
    import {login} from './login';
    
    Vue.use(Vuex);
    
    export default new Vuex.Store({
      modules: {
        todos,
        login,
      }
    });

    Go to the main.ts file, set login module to be lazy load:

    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;
    
    const load = true;
    if (load) {
      import('./store/login').then(({login}) => {
        store.registerModule('login', login);
      });
    }
    
    new Vue({
      router,
      store,
      render: (h) => h(App),
    }).$mount('#app');

    We can use dynamic import syntax to lazy load login store.

    To support the syntax, we need to change "compilerOptions.modules='esnext'".

    To code safty. in login component, we add v-if to check the login module is loaded or not:

    <template>
        <section v-if="login">
            <button v-if="!login.isLoggedIn" @click="loginMutation">Login</button>
            <p v-else>Hello {{login.user}}</p>
        </section>
    </template>
    
    <script lang="ts">
    import {Component, Vue} from 'vue-property-decorator';
    import {State, Mutation} from 'vuex-class';
    import {LoginState} from '../types';
    
    @Component()
    export default class Login extends Vue{
        @State login: LoginState;
        @Mutation('login') loginMutation;
    }
    </script>
  • 相关阅读:
    fibnacci数列的python实现
    求最大公约数伪代码
    2020-2021-1 20201213信息安全专业导论第五周学习总结
    2020级201213《信息安全专业导论》第五周学习总结
    xor加密的python实现
    第四周学习总结
    BASE64编码
    师生关系
    2020-2021--1 20201205《信息安全专业导论》第2周学习总结
    师生关系
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10784731.html
Copyright © 2011-2022 走看看