我创建了一个自定义插件,用vuex和vue-authenticate封装了一堆身份验证功能 .
我遇到的问题是找出正确的方法来加载和安装模块到VueJS,我不知道它是我的webpack或vuejs知识缺乏但到目前为止我有以下
/node_modules/plugin/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import routes from './routes'
import store from './vuex/store'
import EventBus from './bus/eventBus'
import config from './config'
import ping from './vuex/modules/apiArchitect/ping/store'
import auth from './vuex/modules/apiArchitect/auth/store'
import user from './vuex/modules/apiArchitect/user/store'
Vue.use(Vuex)
Vue.use(EventBus)
const store = new Vuex.Store({
modules: {
ping,
user,
auth
},
strict: true
})
let apiArchitect = {}
apiArchitect.install = function (Vue, options) {
Vue.prototype.$apiArchitect = store,
Vue.prototype.$apiArchitect.$config = config
Vue.prototype.$apiArchitect.$routes = routes
if (typeof window !== 'undefined' && window.Vue) {
window.Vue.use(apiArchitect)
}
}
export default apiArchitect
/src/main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import apiArchitect from 'vue-apiarchitect'
import addRouteGuards from 'vue-apiarchitect/src/addRouteGuards'
Vue.config.productionTip = false
Vue.config.env = process.env.NODE_ENV
Vue.use(router)
Vue.use(apiArchitect)
console.log(apiArchitect)
addRouteGuards(router)
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
})
到目前为止,我能够导入插件并使用Vue.use运行安装钩子(apiArchitect)我可以访问它 . $ apiArchitect在我的App.vue中 .
我遇到的问题是插件提供了存储在$ apiArchitect.routes中的一些auth路由,这些路由需要与路由器提供的路由合并 . 如果我尝试访问main.js中的$ apiArchitect.routes,我会收到一个'undefined'错误,我只能在实例化vue后访问它们 . 如果我实际上在main.js中尝试console.log apiArchitect,我看到的是一个包含安装功能的对象,没有我提供的插件,这让我觉得它没有正确安装 .
有谁知道我如何访问main.js中的apiArchitect . $ routes属性或更好的方法来实现这一目标?
谢谢
1 回答
您可以使用
router.addRoutes()
动态添加路由,自2.2.x开始 .例如,您可以在根组件的
created
钩子中使用addRoutes
: