Im создает настраиваемый плагин, который инкапсулирует кучу функций аутентификации с помощью vuex и vue-authenticate.
Проблема im заключается в том, чтобы выяснить правильный способ загрузки и установки модуля в VueJS, im не уверен, что у него отсутствуют мои знания веб-пакета или 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.
Проблема в том, что плагин предоставляет некоторые auth-маршруты, хранящиеся в $ apiArchitect.routes, эти маршруты должны быть объединены с маршрутами, предоставляемыми маршрутизатором. Если я попытаюсь получить доступ к $ apiArchitect.routes в main.js, я получаю сообщение об ошибке "undefined". Я могу получить к ним доступ только после того, как vue был создан. Если я на самом деле попробую console.log apiArchitect в main.js, все, что я вижу, это объект, содержащий функцию установки, ни один из плагина, который я предоставил, что заставляет меня верить в то, что он неправильно установлен.
Кто-нибудь знает, как я могу получить доступ к атрибуту apiArchitect. $ Routes в main.js или к лучшему способу его достижения?
Спасибо
Динамические маршруты можно добавлять с помощью router.addRoutes()
начиная с версии 2.2.x.
Аргумент должен быть массивом, используя тот же формат конфигурации маршрута с опцией конструктора маршрутов.
Например, вы можете использовать addRoutes
в created
крюке корневого компонента:
// your plugin
const myPlugin = {
install: function(Vue, options) {
Vue.prototype.$myPlugin = {
routes: [{
path: '/myplugin', component: options.myComponent
}]
}
}
}
// components
const testComponent = { template: '<p>Component called by plugin route</p>' }
const Home = { template: '<p>Default component</p>' }
// router
const router = new VueRouter({
routes: [{
path: '/', component: Home
}]
})
Vue.use(VueRouter)
Vue.use(myPlugin, { myComponent: testComponent })
new Vue({
el: '#app',
router,
created() {
this.$router.addRoutes(this.$myPlugin.routes); // dinamically add routes
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
<button @click="$router.push('/')">Home</button>
<button @click="$router.push('/myplugin')">Custom</button>
<router-view></router-view>
</div>