从Vue中的api加载路由 [英] Load routes from api in vue

查看:384
本文介绍了从Vue中的api加载路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to load routes in a Vue application from my API. I tried pushing data to routes variable and using addRoutes method. But no luck. I think there could be an issue with async. But why the addRoutes() not working?

这是我的代码:

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
});

推荐答案

尝试以下改进的代码.不延迟Vue实例的创建,因此也没有不必要的延迟页面交互性的作用:

Try this improved code. Without postponing Vue instance creation, so without unnecessary delaying page interactivity:

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')
  }
})

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

For better code structure and readability, move router definition to separate file:

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

In your main file, leave just this code:

// 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":

And in same folder as main file lies, create subfolder 'router' with 'index.js' within:

// 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}
  }]
})

这篇关于从Vue中的api加载路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆