【问题标题】:How to pass props parameter with axios in Vuejs?如何在 Vuejs 中使用 axios 传递 props 参数?
【发布时间】:2020-06-29 18:42:59
【问题描述】:

我正在通过 props 传递另一个组件中的属性:

props: ['product']

此产品具有一些属性,例如:idname 等。

现在,我想通过 axios 获取这个带有 id 的产品的类别。

有可能吗?如何? 我的尝试:

mounted () {
   axios
   .get('/categoryofaproduct/', {
       params: {
          id: this.product.id
       }
   })
   .then(response => {
       console.log(response)
  })
}

【问题讨论】:

  • 什么不起作用?假设您使用的是 Express.js,您应该能够在您的服务器文件中获得 idrequest.query.id

标签: vue.js vuejs2 axios


【解决方案1】:

我认为Props 属性将无法像这样直接访问。

data() {
  return {
     id: null,
     categoryName: null
  }
}

在mounted中,你可以像这样复制id,然后它就可以工作了。

mounted () {
  this.id = this.product.id
  axios.get('/categoryofaproduct/'+this.id)
    .then(response => {
      this.categoryName = response.data
    })
}

【讨论】:

    【解决方案2】:

    我建议使用反引号使其成为字符串文字并使用插值来插入值。当您在 URL 中有多个参数时,这只会使其更具可读性

    mounted () {
       axios
       .get(`/categoryofaproduct/${this.product.id}`
                     
    )
       .then(response => {
           console.log(response)
      })
    }
    

    然后在您的路线上接受该参数

     {
          // create route with id as a parameter
          path: "/categoryofaproduct/:id",
          name: "category-of-a-product",
          component: () => import("./views/categoryofaproduct.vue"),
        },
    

    要访问该参数,请创建一个返回它的计算字段

     computed: {
        paramsId() {
          return this.$route.params.id
        },
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-31
      • 1970-01-01
      • 2019-06-05
      • 2019-03-29
      • 2018-08-17
      • 1970-01-01
      • 2019-03-08
      • 2021-10-13
      相关资源
      最近更新 更多