VueJS动态路线和组件

时间:2018-09-26 22:30:26

标签: vue.js vuejs2 vue-component

使用cue-cli 3.是否可以执行此操作(router.js):

axios.get( `${process.env.VUE_APP_API_DOMAIN}/wp-json/api/v1/routes`).then( r => r.data ).then(routes => {
    routes.pages.forEach( (e) => {
        router.addRoutes([
            {
                path: `/${e.slug}`,
                component: e.template,
            },
        ]);
    });
});

e.template是字符串'Default',当然VueJS表示: route config "component" for path: /privacy-policy cannot be a string id. Use an actual component instead.试过Vue.component(e.template),没有运气。

我在这里要做的是基于XHR响应创建动态路由。

这是所有router.js代码:

import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import Default from './views/Default.vue'
import Test from './views/Test.vue'
import axios from "axios";

Vue.use(Router);

const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    },
  ]
});

axios.get( `${process.env.VUE_APP_API_DOMAIN}/wp-json/api/v1/routes`).then( r => r.data ).then(routes => {
    routes.pages.forEach( (e) => {
        router.addRoutes([
            {
                path: `/${e.slug}`,
                component: e.template,
            },
        ]);
    });
});

export default router;

2 个答案:

答案 0 :(得分:1)

如果e.template存储模板字符串,则

您应该将其包装为一个{template: e.template, props: {}, data: function () {} }之类的选项对象,然后调用Vue.extend来构造组件。

或者您可以忽略Vue.extend,因为Vue会调用Vue.extend自动构建组件。

通过Vue Guide: Vue.component

检查使用情况

编辑,因为OP指出e.tempate是一个组件名称:

如果e.template是组件的名称,则使用Vue.component(e.template)

Vue.config.productionTip = false
const router = new VueRouter({
  routes: [
  ]
})

Vue.component('test', {
  template: '<div>I am Predefined component -> {{index}}</div>',
  props: ['index']
})

let routerIndex = 1
setInterval(()=> {
  let newComponent = routerIndex%2 ? {template: '<div>I am User -> {{index}}</div>', props: ['index']} : Vue.component('test')
  
  router.addRoutes([{
    path: '/Test' + routerIndex,
    name: 'Test' + routerIndex,
    component: newComponent,
    props: { index: routerIndex }
  }])
  console.log('add route = ', '/Test' + routerIndex, ' by ', routerIndex%2 ? 'options object' : 'Vue.component')
  routerIndex++
}, 2000)

Vue.use(VueRouter)
app = new Vue({
  el: "#app",
  router,
  data: {
    routeIndex: 0
  },
  watch: {
    routeIndex: function (newVal) {
      this.$router.push({'name': 'Test'+newVal})
    }
  }
})
div.as-console-wrapper {
  height: 100px;
}
<script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
    <p>Current Route Index: {{routeIndex}}</p>
    Test Route: <input v-model="routeIndex" type="number">
    <router-view></router-view>
</div>

答案 1 :(得分:0)

目前,我得到了以下解决方案:

ID

另一种更清洁的解决方案:

function getComponent(name) {

    let component = null;

    switch(name)
    {
        case 'Default':
            component = Default;
            break;

        case 'Test':
            component = Test;
            break;
    }

    return component;

}

axios.get( `${process.env.VUE_APP_API_DOMAIN}/wp-json/api/v1/routes`).then( r => r.data ).then(routes => {
    routes.pages.forEach( (e) => {
        router.addRoutes([
            {
                path: `/${e.slug}`,
                component: getComponent(e.template),
            },
        ]);
    });
});