具有相同路线和相同组件的两条路径 - Vue js

时间:2017-11-07 14:38:04

标签: vue.js vuejs2 vue-router

我有两条相同组件的路径:

/:loc("-host") - 应匹配/ usa-host

/:loc/:sublocation("-host") - 应匹配/ usa / washington-host

如何使用vue.js中的单个命名路由实现此目的

2 个答案:

答案 0 :(得分:2)

这是我的解决方案。

<强>路由器:

使用?将param与路线中的文字分开。

const router = new VueRouter({
  routes: [
    { path: '/', component: Home },
    { path: '/:loc/:subloc?-host', component: Location },
    { path: '/:loc?-host', component: Location },
  ]
})

组件:

从$ route.params设置局部变量。

const Location = { 
  template: '<div>Location {{loc}} - {{ subloc }}</div>',
  data: function () {
    return {
      loc: this.$route.params.loc,
      subloc: this.$route.params.subloc,
    }
  },
}

<强>模板:

使用:key="$route.fullPath"确保组件重新创建每个导航。

<div id="app">
  <router-link to="/">Home</router-link> |
  <router-link to="/usa-host" >loc1</router-link> |
  <router-link to="/usa/washington-host"  >loc2</router-link>
  <router-view :key="$route.fullPath"></router-view>
</div>


Fiddle here

答案 1 :(得分:1)

您可以使用路径的别名

const router = new VueRouter({
  routes: [
    { path: '/a', component: A, alias: '/b' }
  ]
})

签入Why array implements IList?

&#13;
&#13;
const Home = { template: '<div>Home</div>' }
const Project = { 
	template: '<div>Project {{id}}</div>',
  mounted(){
  	console.log(this.$route);
  },
  data: function () {
    return {
    	id:this.$route.params.id||'',
    }
  }
}

const router = new VueRouter({
  mode: 'history',
  routes: [
  {
    path: '/',
    component: Home
  },
  {
    path: '/projects/:id?',
    component: Project,
    alias: '/project/:id'
  }
]
})

new Vue({
	router,
  el: '#app'
})
&#13;
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

<div id="app">
<router-link to="/">Home</router-link> |
<router-link to="/projects">projects</router-link> |
<router-link to="/project/1">project/1</router-link>
<router-view></router-view>
</div>
&#13;
&#13;
&#13;

同时检查小提琴:doc

注意:默认情况下打开相同的组件不起作用,您需要使用其他技巧。如果只是对小提琴进行测试,请转home - &gt; /projectshome - &gt; /project/1,但/projects - &gt; /project/1/project/1 - &gt; /projects无法使用。要使其工作,请执行以下操作:https://jsfiddle.net/nikleshraut/9sgk6yg4/1/