【问题标题】:VueJS route params objectVueJS 路由参数对象
【发布时间】:2020-12-16 10:07:30
【问题描述】:

我正在检查某人的代码。它们在计算中具有以下内容:

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}。

但是这里的教练正在路由中被访问,它显然是一个对象?我不明白这怎么可能

【问题讨论】:

  • 查看 router.js
  • 计算属性可以注入模板,你可以在这里找到文档docs
  • 请看看我的编辑
  • 代码有效吗?还是 &lt;p class="name"&gt;{{coach.last_name}}{{coach.first_name}}&lt;/p&gt; 呈现为 undefinedundefined

标签: javascript vue.js vuejs2


【解决方案1】:

好吧,我不确定这是否是正确的做法,但 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.

【讨论】:

  • 我认为在$route.push({name: xxx, params: {obj: {test: 'test'}}}) 中传递对象是不可能的,因为我总是遇到错误并且必须对对象进行字符串化,因为错误表示只能在参数中发送字符串。你确定上面的代码有效吗?
  • 是的,我已经尝试过并使用过。所以我很确定:)
猜你喜欢
  • 1970-01-01
  • 2020-02-15
  • 2023-03-27
  • 2018-02-04
  • 2018-05-29
  • 1970-01-01
  • 2017-11-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多