Muk*_*mar 3 vue.js vue-router vuejs2
我有两条具有相同组件的路径,如下所示:
/:loc("-host") - 应该匹配 /usa-host
/:loc/:sublocation("-host") - 应该匹配 /usa/washington-host
如何在 vue.js 中使用单个命名路由来实现这一点
您可以使用路径别名
const router = new VueRouter({
routes: [
{ path: '/a', component: A, alias: '/b' }
]
})
Run Code Online (Sandbox Code Playgroud)
签入文档
const router = new VueRouter({
routes: [
{ path: '/a', component: A, alias: '/b' }
]
})
Run Code Online (Sandbox Code Playgroud)
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'
})Run Code Online (Sandbox Code Playgroud)
还要检查小提琴:https : //jsfiddle.net/nikleshraut/9sgk6yg4/1/
注意:默认情况下无法打开相同的组件,您需要使用其他技巧。只是测试上面的小提琴,去home->/projects和home->/project/1会工作,但/projects->/project/1或/project/1->/projects不会工作。要使其工作,请执行以下操作:https : //jsfiddle.net/nikleshraut/9sgk6yg4/
这是我的解决方案。
路由器:
用于?将路径中的参数与文字分开。
const router = new VueRouter({
routes: [
{ path: '/', component: Home },
{ path: '/:loc/:subloc?-host', component: Location },
{ path: '/:loc?-host', component: Location },
]
})
Run Code Online (Sandbox Code Playgroud)
成分:
从 $route.params 设置局部变量。
const Location = {
template: '<div>Location {{loc}} - {{ subloc }}</div>',
data: function () {
return {
loc: this.$route.params.loc,
subloc: this.$route.params.subloc,
}
},
}
Run Code Online (Sandbox Code Playgroud)
模板:
用于: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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8898 次 |
| 最近记录: |