为方便学习,已放 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项目地址 链接