【问题标题】:Passig a data via "this.$router.push" in vue.js通过 vue.js 中的“this.$router.push”传递数据
【发布时间】:2020-08-10 09:05:48
【问题描述】:

我正在使用 Django REST 和 Vue.js 编写一个餐厅评论项目。我使用 google place ID 作为我的餐厅的 PK,因为 Google Place ID 是唯一的,并且我在我的项目中使用 Google Place Autocomplete。

所以基本上我有一个自动完成功能,只要用户选择它,它就会获取餐厅地点 ID。 然后我想自动重定向到另一条路线,在那里我将使用该 Google Place ID 通过 API (/api/restaurant_review/Google Place ID/) 获取该餐厅的所有评论。

这是我的导航栏组件:

<template>        
      <div class="collapse navbar-collapse flex-row justify-content-end">
        <vue-google-autocomplete
          id="map"
          class="form-control mr-sm-2"
          placeholder="Find a restaurant"
          v-on:placechanged="getAddressData"
          country="fr"
          types="establishment"
        ></vue-google-autocomplete>
</template>


<script>
import VueGoogleAutocomplete from "vue-google-autocomplete";
export default {
  name: "NavbarComponent",
  components: { VueGoogleAutocomplete },
  data() {
    return {
      requestUser: null,
      addressData: ""
    };
  },
  created() {
    this.setRequestUser();
  },
  methods: {        
    getAddressData(addressData, placeResultData) {
      this.placeResultData = placeResultData;
      this.addressData = addressData;          
      this.$router.push({ name: "reviews", params: { id : this.placeResultData.place_id }})
    }
  }
};
</script>

现在我制作了一个虚拟的“评论”视图,只显示“Hello World”消息。重定向工作正常,但我找不到检查我的“id”是否在我的评论视图中可用的方法。而且我也不知道这是否是正确的方法。另外,是否可以传递多个参数?

【问题讨论】:

  • 在我的“评论”视图中,我将有一个模板来显示所有带有 v-for 循环的评论。我将从 API 服务获取所有评论,该服务将连接到以我的 Google Place Id 作为参数的端点。我只是想问是否像我一样做,所选餐厅的 Google Place Id 是否会出现在“评论”视图中?

标签: javascript vue.js


【解决方案1】:

official guide 中所述,您可以为您的可路由组件定义 props(例如 “review”)并让 Vue Router 传入任何路由参数。

例如,在您的路线定义中

{
  name: "review",
  path: "/review/:id",
  component: Review,
  props: true // ? convert path parameters like "id" to props
}

然后在您的组件中,类似于以下内容

export default {
  props: { id: String } // ? passed in via the :id route parameter
  async created () {
    const response = await apiCall(`/api/restaurant_review/${encodeURIComponent(this.id)}`)
  }
}

是否可以传递多个参数?

当然。您可以定义任意数量的路由参数,例如

{
  path: "/my-path/:foo/:bar/:baz"
}

使用$router.push() 时,您还可以传入不属于路径的额外参数。例如,使用上面的 reviews 路由

this.$router.push({ name: "reviews", params: {
  id: this.placeResultData.place_id,
  title: this.placeResultData.name // ? just guessing here
}})

然后您可以通过以下方式访问这些内容

this.$route.params.title

或定义道具,但对于这些我建议将它们设为可选,因为它们不会来自路径,因此不能来自直接链接

props: {
  fromPath: String, // from path and required
  optionalParam: {
    required: false,
    default: "Some default value
  }
}

【讨论】:

    猜你喜欢
    • 2018-05-13
    • 2023-03-04
    • 2020-04-24
    • 2020-10-30
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    相关资源
    最近更新 更多