Vuex 异步加载

为方便学习,已放 github

Vue-cli3 下载基础的模板

有两个模板,Home.vue和About.vue

我在Home.vue下使用vuex, About未使用

在这里插入图片描述

路由导入文件修改

import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/',
      name: 'home',
      component:()=>import('./views/Home.vue')
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (about.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('./views/About.vue')
    }
  ]
})

Home.vue 关键是代码文件目录结构,vuex可以跟自己项目对应好,尤其是使用modules后文件导入

<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png">
    <div>
        {{ count }}
    </div>
    <div>
      <button @click="add(2)">添加</button>
    </div>
  </div>
</template>

<script>
// @ is an alias to /src
// import HelloWorld from '@/components/HelloWorld.vue'
import { mapState, mapActions } from 'vuex'

export default {
  name: 'count',
  isVuex:true,
  components: {
    // HelloWorld
  },
  computed: {
    ...mapState({
      count: state => state.count.count
    })
  },
  methods: {
    ...mapActions(['count/reqApi']),
    add(num){
      //  console.log(this)
       this['count/reqApi']();
    }
  },
  mounted () {
    console.log()
  }
}
</script>

npm run build

在这里插入图片描述
用到Vuex的地方

export default {
  name: 'count',  //这里原来是home 的name  这里要更vuex的modules中的对应模块一致     
  isVuex:true,
  // ...
}

myplugins

// 这篇入门文章的关键,就在这几行代码上
export default  {
    install: function(Vue){
        Vue.mixin({
            created(){
                // console.log(this.$options)
                if(this.$options.isVuex){
                    import('../store/modules/'+this.$options.name).then((res)=>{   //在这里就说明为什么name要一致,方便查找对应的vuex
                        this.$store.registerModule(this.$options.name,res.default);
                    })
                }
            }
        })
    }
}

main.js

// 入口文件引用

import plugins from './myplugins'

Vue.use(plugins)

npm run build

在这里插入图片描述

github项目地址 链接

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值