模板无法捕捉到计算属性的内容,但生命周期钩子可以正常记录
P粉604669414
P粉604669414 2023-08-30 23:44:38
0
1
486
<p>我正在创建一个网店,在这里您可以选择在不干扰购物车内容的情况下订购产品。我实现的方式是共享一个页面,用于购物车项目和单个产品。它会检查是否设置了productID参数,如果是,则使用不同的数据。</p> <p>这是我编写的函数:</p> <pre class="brush:js;toolbar:false;"> computed : { products: function() { if ( this.$route.query.pid ) { var product = [{}] axios.get(`/api/products/${this.pid}`).then(response => { product[0].id = response.data[0].id product[0].name = response.data[0].name product[0].units = response.data[0].units product[0].image = response.data[0].product_image[0].image product[0].price = response.data[0].price product[0].quantity = 1 }) return Object.assign(product) } else { return this.$store.state.cart } } }, </pre> <p>这是成功获取数据的生命周期钩子(beforeMount):</p> <pre class="brush:js;toolbar:false;"> beforeMount() { console.log(this.products) } </pre> <p>现在的问题是,模板中将products属性视为空。当我不带查询参数访问该页面时,一切正常,只是无法找到单个产品的计算数据。</p> <p>如何解决这个问题?提前感谢您的帮助!</p>
P粉604669414
P粉604669414

全部回复(1)
P粉665679053

vue/no-async-in-computed-properties

属性在模板中没有被捕获,但生命周期钩子可以通过计算属性获取数据

你在控制台中看到的原因是因为大多数现代浏览器将对象作为实时数据记录(一旦对象更新,控制台也会更新)。所以你在控制台中看到的不是console.log执行时对象的值,而是稍后的值。你可以通过使用console.log(JSON.parse(JSON.stringify(this.products)))来确认这一点...

为了解决这个问题,使用watch而不是computed

data() {
  return {
    products: []
  }
},
watch: {
  '$route.query.pid': {
    handler: function(newValue) {
      if(newValue) {
        axios.get(`/api/products/${newValue}`).then(response => {
          var product = {
            id: response.data[0].id,
            name: response.data[0].name,
            units: response.data[0].units
            image: response.data[0].product_image[0].image
            price: response.data[0].price
            quantity: 1
          }
          this.products = []
          this.products.push(product)
      } else this.products = this.$store.state.cart
    },
    immediate: true
  }
},
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!