Vue Router - 从 JSON 构建 [英] Vue Router - build from JSON

查看:68
本文介绍了Vue Router - 从 JSON 构建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Vue.js 很陌生.我习惯了普通的 JavaScript.
我需要能够从 JSON 文件生成路由路径.
我怎样才能实现它?

编辑

例如,假设这是我的 JSON:

<预><代码>[{"name": "产品 1","url": "product-1",},{"name": "产品 2","url": "product-2",}]

我基本上需要 Vue Router 将 URL/product-1 重定向到产品 1 的组件(这将是 ) 和 URL/product-2 到产品 2 的组件 ()

解决方案

假设你的组件在对象中的名称是 name,我们需要将你的结构与 Vue Router API.因此,我们可以这样做:

const myRoutes = [{"name": "产品 1","url": "product-1",},{"name": "产品 2","url": "product-2",}]const 路由器 = 新的 VueRouter({路线:myRouters.map(({name, url})=>({component: name, path: `/${url}`)),})

I'm quite new to Vue.js. I'm used to vanilla JavaScript.
I need to be able to generate route paths from a JSON file.
How can I achieve it?

EDIT

For example, say this is my JSON:

[
  {
    "name": "Product 1",
    "url": "product-1",
  },
  {
    "name": "Product 2",
    "url": "product-2",
  }
]

I basically need Vue Router to redirect URL/product-1 to Product 1's component (which will be <Product-1></Product-1>), and URL/product-2 to Product 2's component (<Product-2></Product-2>)

解决方案

Assuming your component's name is name in the object, we need to match your structure to Vue Router API. Thus, we can do as follows:

const myRoutes = [
  {
    "name": "Product 1",
    "url": "product-1",
  },
  {
    "name": "Product 2",
    "url": "product-2",
  }
]

const router = new VueRouter({
  routes: myRouters
          .map(({name, url})=>({component: name, path: `/${url}`)),
})

这篇关于Vue Router - 从 JSON 构建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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