vue.js - (Vue路由器)在特定路线上推送参数
问题描述
我有一个组件,它具有基于外部数据的程序化路由。外部数据在组件中获取App.vue
并在子组件中用作props
.
数据在子组件中使用如下:
props: {
externalData: Array
},
computed() {
data() {
return this.externalData
}
}
这是我的router.js
(摘录)
const routes = [
{
path: "/:hae?",
name: "Home",
component: Home
},
{
path: "*",
name: "NotFound",
component: NotFound
}
];
而我Home.vue
的$router.push
方法(摘录):
created() {
if (this.$route.path === "/") {
this.$router.push({
params: {
hae: this.data[0].id
}
});
}
},
所以这就是我想要实现的目标:
这是我的示例数组:[{hae: "hae001"}, {hae: "hae002"}, {hae: "hae003"} ...]
当您导航到https://website.com/
我希望路由器将您重定向到作为数组的第一个元素的参数,但是如果您导航到数组中不存在的其他位置(例如/something
)我想要路由器渲染我的NotFound.vue
组件。
我错过了什么?
解决方案
created() {
const firstDataElementExists = this.data && this.data[0] && this.data[0].hae
if (!firstDataElementExists) {
this.$router.push('/404')
return
}
const isRootPath = this.$route.path === '/'
if (isRootPath) {
this.$router.push(this.data[0].hae)
return
}
const pathIsInData = !!this.data.find(d => d.hae === p)
if (!isRootPath && !pathIsInData) {
this.$router.push('/404')
}
}
推荐阅读
- c - C程序从用户那里获取联系并将其添加到文件中
- php - 带有 Shopify 403 Forbidden 的 PHP Curl(API 访问范围未定义)
- spring-boot - Spring Batch 动态查询 JdbcPagingItemReader 并在步骤之间传递数据
- oracle - 无法使用 APEX_WEB_SERVICE 从 Oracle RDS 实例运行 REST API
- javascript - 我有两个站点,site.com1 和 site2.com 我想检查用户是否使用 PHP 从 site1 登录到 site2
- python - 如何使用python从表中获取所有列并将其作为csv文件保存在s3中
- java - 使用 IBM MQ 在 JmsTemplate.send 期间处理连接失败
- c - 使用联合处理错误
- python - 没有 for 或 while 循环的字典递归
- sql - SQL Server 查找包含的组