繁体   English   中英

通过 vue.js 中的“this.$router.push”传递数据

[英]Passig a data via “this.$router.push” in vue.js

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

所以基本上我有一个自动完成功能,每当用户 select 时,我都会获得一个餐厅地点 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”是否在我的评论视图中可用的方法。 而且我也不知道这是否是正确的方法。 同样,是否可以传递多个参数?

官方指南中所述,您可以为您的可路由组件定义道具(例如“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()时,您还可以传入不属于路径的额外参数。 例如,使用上面的评论路线

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM