从vue中的api加载路由

2024-05-03

我正在尝试从我的 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
});

尝试这个改进的代码。无需推迟 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}
  }]
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从vue中的api加载路由 的相关文章

随机推荐

  • 获取:使用获取响应设置变量并从函数返回[重复]

    这个问题在这里已经有答案了 我对 JavaScript 和 React 还很陌生 我有一个来自组件的回调 该组件从给定 id 的服务器获取 customer name 提取工作正常 console log 正确打印全名 但最后一个 then
  • 在 JavaScript 中压缩 Blob

    我需要使用 ajax 向服务器发送一个 blob 但它最终可能会变得有点大 我想减少上传时间 我已经尝试过 jszip 但这只是在 zip 中给了我一个空文件 我也尝试过 btoa 但事实证明编码值最终只是 object Blob 而不是实
  • 使用存储桶级别权限调用 PutObject 操作时出现访问被拒绝的情况

    我按照上面的例子http docs aws amazon com IAM latest UserGuide access policies examples html iam policy example s3 http docs aws
  • 如何使 UL 元素内的列表项居中?

    如何在不使用额外的 div 或元素的情况下将列表项集中在 ul 内 我有以下内容 我想text align center就可以了 我似乎无法弄清楚 ul li test li li test li li test li li test li
  • 我应该使用哪种协议来传输音频(非直播)? [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • 使用 MySQL 5、简单成员资格提供程序、ASP.NET MVC4 和实体框架 5

    我在尝试着 使用 ASP NET MVC 4 对 MySQL 使用基于简单成员资格提供程序的身份验证默认 Web 应用程序配置为使用 MySQL 使用以下给出的教程 http www nsilverbullet net 2012 11 07
  • 仅复制对象一部分的优雅方法[重复]

    这个问题在这里已经有答案了 我想通过仅复制其中的一些属性来从更大的对象创建一个新对象 我所知道的所有解决方案都不是很优雅 我想知道是否有更好的选择 如果可能的话是原生的 没有像下面代码末尾那样的附加功能 这是我现在通常做的事情 I want
  • Swing 组件 - 禁用布局中的调整大小

    我有一个自定义 GUI 组件 它基于 Swing 的 JPanel 该组件放置在使用 BorderLayout 的 JFrame 中 当我调整框架大小时 该组件会不断调整大小 我怎样才能避免这种情况 我希望组件无论发生什么情况都保持相同的大
  • 将表情符号列表替换为其图像

    我有一个数组 emoticons smile1 gif smile2 gif D smile3 gif 然后我有一个带有文本的变量 var text this is a simple test 和一个带有网站 url 的变量 var url
  • 同位素网格+角印去除空白,排序逻辑

    这个问题与这个旧问题有关 同位素网格布局使用空白空间 https stackoverflow com questions 11612399 isotope grid layout use empty space 这是我正在使用的小提琴 ht
  • 如何使用过程填充数据库

    我有大约 15 个不同的表 其中填充了不同的数据和不同的实体关系 我需要创建一个脚本 用这些表的内容填充我的数据库 脚本完成后 我使用 sqlplus 在 cmd 中运行它 然后使用 START文件路径 我有两个不同的 sql 文件 一个名
  • Python C-Api 线程问题

    我正在编写一个 C 程序 它使用用 python 编写的网络库 我将 python lib 与 python C api 一起嵌入 该库异步发送所有请求 并在请求完成时通过信号通知我 这意味着理论上 实际上我有两个与线程相关的问题 从 c
  • 现代正则表达式引擎可以解析什么样的形式语言?

    人们有时会说 你不能用正则表达式解析 X 因为 X 不是正则语言 然而 根据我的理解 现代正则表达式引擎可以匹配的不仅仅是正则语言乔姆斯基的感觉 http en wikipedia org wiki Chomsky hierarchy 我的
  • Android:Google 登录令牌无效

    我通过 Android 中的 google 登录收到的令牌收到错误 error invalid token error description 无效值 我还注意到 与我在 iOS 中获得的令牌相比 我的令牌看起来有点短 ya29 4AFYx
  • Laravel 关注者/关注关系

    我正在尝试在 laravel 中制作一个简单的关注者 关注系统 没什么特别的 只需单击一个按钮即可关注或取消关注 并显示关注者或关注你的人 我的问题是我不知道如何建立模型之间的关系 这些是迁移 用户迁移 Schema create user
  • Shell 执行将窗口置于前面

    我正在使用此函数从我的 MSI 调用可执行文件 然而 可执行文件的窗口隐藏在我的 MSI 窗口后面 有什么办法可以把它带到前面吗 我尝试在调用之前最小化所有窗口ShellExecute但这仍然没有将可执行窗口带到前面 extern C UI
  • typescript 扩展不需要的接口

    我有两个接口 interface ISuccessResponse Success boolean Message string and interface IAppVersion extends ISuccessResponse OSVe
  • 有 PostSharp 替代品吗? [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我必须放弃使用 PostSharp 因为它不适用于混淆 合并的程序集 至少 我没有看到任何方法让它工作
  • 如何在 Python 3.x 中删除字符串末尾的数字?

    我想从字符串末尾删除数字 但我不知道 Can the split 方法工作 我怎样才能做到这一点 初始字符串看起来像asdfg123 而我只想asdfg反而 感谢您的帮助 不 split 不起作用 因为 split 只能与要分割的固定字符串
  • 从vue中的api加载路由

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