javascript - VueJS 路由参数对象
问题描述
我正在检查某人的代码。他们在计算中具有以下内容:
computed: {
requireParams() {
return {
coach: this.coach,
sid: this.sid
};
},
coach() {
return this.$route.params.coach || {};
},
sid() {
return this.$route.params.sid || null;
},
avatar() {
if (
this.coach.profile_pic &&
this.coach.profile_pic.indexOf("http") !== -1
) {
return this.coach.profile_pic;
} else {
return "/images/_avatar.jpg";
}
}
}
现在在 html 模板代码中,coach 被多次引用,就像这样
<p class="name">{{coach.last_name}}{{coach.first_name}}</p>
谁能解释一下教练是如何在路线上发送的?我认为只能在路由中发送字符串,例如 /path/:id 会转换为 /path/2,因此 $route.params 会给出 {id: 2}。
但是这里的教练正在路线中被访问,它显然是一个对象?我不明白这怎么可能
解决方案
好吧,我不确定这是否是正确的方法,但是 Vue 允许您在路由器中传递一个对象。如果你有 vuedevtools,你可以在 vue $route 部分查看:路径、查询、参数、完整路径、名称和元。在 params 我们可以发送一个对象。
例如,您的路线将是这样的:
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about/:id',
name: 'About',
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
}
]
之后让我们创建一个按钮来在路由之间推送我们的数据。
<template>
<div class="home">
<button @click="sendObject">send my object</button>
</div>
</template>
<script>
export default {
name: 'Home',
data() {
return {
myObj: {
id: 1,
name: "George",
surname: "White",
number: 123
}
}
},
methods: {
sendObject() {
this.$router.push({name: 'About', params: {id: this.myObj.id, comingItem: this.myObj}})
}
}
}
</script>
最后让我们把我们的物品带到其他路线,像这样:
<template>
<div class="about">
<h1>This is my object</h1>
<div v-for="att in myItem" :key="att.id">
<div> {{att}}</div>
</div>
</div>
</template>
<script>
export default {
name: "About",
data() {
return {
myItem : null
}
},
created() {
this.myItem = this.$route.params.comingItem
}
}
</script>
Dom 会像:
1 乔治·怀特 123。
推荐阅读
- google-apps-script - 使用 Google Apps 脚本过滤不是来自给定域的电子邮件
- python - python非阻塞套接字避免在发送中复制
- python - 从文本文件加载python中的字典
- ruby-on-rails - 在 Rails 中重定向后更改操作
- javascript - 下载 mp3 格式的 URL
- python - 如何使此命令适用于所有用户
- python-3.x - Anaconda 导航配置存储在哪里?
- python - youtube-dl 和使用它的工具也出错。可能与aria2c有关?
- jenkins - 我们如何使用 `cypress-tags` 在 Jenkins 管道中运行 cypress 测试
- reactjs - 在一个数组中有 2 种形式的字符串,并在 React JS 的运行时动态地在它们之间进行转换