从Vue中的api加载路由

时间:2018-11-03 15:02:30

标签: vue.js axios vue-component vue-router

我正在尝试从我的API加载Vue应用程序中的路由。我尝试将数据推送到路由变量并使用addRoutes方法。但是没有运气。我认为异步可能存在问题。但是为什么addRoutes()不起作用?

这是我的代码:

import Vue from 'vue';
import VueRouter from 'vue-router';
import axios from 'axios';

/**
 * Routes
*/
import item_index from '../../app/Tenant/Item/Views/Index.vue';
import contact_index from '../../app/Tenant/Contact/Views/Index.vue';
import eav_index from '../../app/Tenant/Eav/Views/create.vue';
import eav_create from '../../app/Tenant/Eav/Views/create.vue';

var routes = [
     { path: '/items', component: item_index, name: 'item_index' },
     { path: '/contact', component: eav_index , name: 'contact_index' , props: { entity_type_id: 1 }},
 ];


Vue.use(VueRouter);

const router = new VueRouter({
    mode: 'history',
    linkActiveClass: 'active',
    routes
});

axios
    .get('http://c1.fmt.dev/api/eav/entity_types')
    .then(response => {
        for (var i = 0; i < response.data.length; i++) {
            var type = response.data[i];
            var route = {
                path: '/' + type.name,
                component: eav_index,
                name: type.name + '_index',
                props: {
                    entity_type_id: type.id
                },
            };

            router.addRoutes([route]);
            alert(router.options.routes);
            // alert(JSON.stringify(routes));
        }
    })
    .catch(error => {
        console.log(error)
});

new Vue({
    el: '.v-app',
    data(){
      return {
        page_header: '',
        page_header_small: '',
      }
    },
    router, axios
});

2 个答案:

答案 0 :(得分:4)

尝试以下改进的代码。无需延迟Vue实例的创建,因此也不必不必要地延迟页面交互性:

import Vue from 'vue'
import VueRouter from 'vue-router'
import axios from 'axios'

import item_index from '../../app/Tenant/Item/Views/Index.vue'
import contact_index from '../../app/Tenant/Contact/Views/Index.vue'
import eav_index from '../../app/Tenant/Eav/Views/create.vue'
import eav_create from '../../app/Tenant/Eav/Views/create.vue'

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  linkActiveClass: 'active',

  routes: [{
    path: '/items',
    component: item_index,
    name: 'item_index'
  }, {
    path: '/contact',
    component: eav_index ,
    name: 'contact_index' ,
    props: {entity_type_id: 1}
  }]
})

new Vue({
  el: '.v-app',
  router,

  data () {
    return {
      page_header: '',
      page_header_small: '',
    }
  },

  methods: {
    getDynamicRoutes (url) {
      axios
        .get(url)
        .then(this.processData)
        .catch(err => console.log(err))
    },

    processData: ({data}) => {
      data.forEach(this.createAndAppendRoute)
    },

    createAndAppendRoute: route => {
      let newRoute = {
        path: `/${route.name}`,
        component: eav_index,
        name: `${route.name}_index`,
        props: {entity_type_id: route.id}
      }

      this.$router.addRoutes([newRoute])
    }
  },

  created () {
    this.getDynamicRoutes('http://c1.fmt.dev/api/eav/entity_types')
  }
})

为获得更好的代码结构和可读性,请将路由器定义移至单独的文件:

在您的主文件中,仅保留以下代码:

// main.js
import Vue from 'vue'   
import router from '@/router'
import axios from 'axios'

new Vue({
  el: '.v-app',
  router,

  data () {
    return {
      page_header: '',
      page_header_small: '',
    }
  },

  methods: {
    getDynamicRoutes (url) {
      axios
        .get(url)
        .then(this.processData)
        .catch(err => console.log(err))
    },

    processData: ({data}) => {
      data.forEach(this.createAndAppendRoute)
    },

    createAndAppendRoute: route => {
      let newRoute = {
        path: `/${route.name}`,
        component: eav_index,
        name: `${route.name}_index`,
        props: {entity_type_id: route.id}
      }

      this.$router.addRoutes([newRoute])
    }
  },

  created () {
    this.getDynamicRoutes('http://c1.fmt.dev/api/eav/entity_types')
  }
})

在与主文件所在的文件夹中,使用以下文件夹中的“ index.js”创建子文件夹“ router”:

// router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'

import item_index from '../../../app/Tenant/Item/Views/Index.vue'
import contact_index from '../../../app/Tenant/Contact/Views/Index.vue'
import eav_index from '../../../app/Tenant/Eav/Views/create.vue'
import eav_create from '../../../app/Tenant/Eav/Views/create.vue'

Vue.use(VueRouter)

export default new VueRouter({
  mode: 'history',
  linkActiveClass: 'active',

  routes: [{
    path: '/items',
    component: item_index,
    name: 'item_index'
  }, {
    path: '/contact',
    component: eav_index ,
    name: 'contact_index' ,
    props: {entity_type_id: 1}
  }]
})

答案 1 :(得分:0)

当您尝试添加路线时,vue实例已经启动(与该问题相同的问题:How to use addroutes method in Vue-router?)。您可以在路由加载后推迟vue初始化:

//imports and stuff...

axios
    .get('http://c1.fmt.dev/api/eav/entity_types')
    .then(response => {
        for (var i = 0; i < response.data.length; i++) {
            var type = response.data[i];
            var route = {
                path: '/' + type.name,
                component: eav_index,
                name: type.name + '_index',
                props: {
                    entity_type_id: type.id
                },
            };

            // extend routes array prior to router init
            routes.push(route);
        }
        // init router when all routes are known
        const router = new VueRouter({
            mode: 'history',
            linkActiveClass: 'active',
            routes
        });

        // init vuw instance when router is ready
        new Vue({
            el: '.v-app',
            data(){
              return {
                page_header: '',
                page_header_small: '',
              }
            },
            router, axios
        });
    })
    .catch(error => {
        console.log(error)
});