首页 > 解决方案 > 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}。

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

标签: javascriptvue.jsvuejs2

解决方案


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


推荐阅读