gpt4 book ai didi

vue.js - 将 vue js 路由与其中的查询字符串匹配?

转载 作者:搜寻专家 更新时间:2023-10-30 22:31:49 25 4
gpt4 key购买 nike

我在这里阅读:

https://router.vuejs.org/en/essentials/dynamic-matching.html

但是好像不让我匹配说:

/mycoolapp?someid=123

是的,我可以做

/mycoolapp/123

但这不是问题

问题是:我可以使用 get 查询参数动态匹配路由吗?

最佳答案

您可以通过 $route.query.someid 访问查询参数,在您的示例 someid 中。 From $route docs :

  • $route.query

    type: Object

    An object that contains key/value pairs of the query string. For example, for a path /foo?user=1, we get $route.query.user == 1. If there is no query the value will be an empty object.

下面的演示:

const UserList = {
template: '#users',
data() { return { users: [] } },
created() {
axios.get('https://jsonplaceholder.typicode.com/users').then(r => this.users = r.data);
}
};
const User = {
props: ['uid', 'user'],
template: '#user'
}

var router = new VueRouter({
routes: [{
path: '/',
component: UserList
},
{
path: '/user/:uid',
component: User,
name: 'user',
props: true
}]
});

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

<template id="users" functional>
<div>
<ul>
<li v-for="user in users">
<div>
{{ user.name }} -
<router-link :to="{name: 'user', params: {uid: user.id, user: user}, query: {field: 'email'}}">(email)</router-link> -
<router-link :to="{name: 'user', params: {uid: user.id, user: user}, query: {field: 'website'}}">(website)</router-link>
</div>
</li>
</ul>
</div>
</template>

<template id="user" functional>
<div class="row">
<b>{{ user.name }}</b><br>
{{ $route.query.field }}: {{ user[$route.query.field] }}<br>
<router-link :to="{path: '/'}">back</router-link>
</div>
</template>

<div id="app">
<p>{{ message }}</p>
</div>

另一方面,如果你想根据查询参数重定向到特定的组件,你可以使用navigation guards。 .例如,beforeEach:

router.beforeEach((to, from, next) => {
if (to.query.field === 'email') {
next({path: '/email'}); // some hypothetical path
} else {
next();
}
});

关于vue.js - 将 vue js 路由与其中的查询字符串匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50053880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com