vue.js - 子事件发生后立即通知父组件?

标签 vue.js

我需要当用户单击子组件上的按钮时,父组件接收 cart.lenght 以分配元素的 count 属性。

子组件代码

<q-btn flat round color="faded" icon="fas fa-shopping-cart" @click="cart(item.id)"/>

cart: function (Id) {
      let cart = []
      cart.push(Id)
      this.$emit('totalItensCart')
      this.$q.localStorage.set('cart', cart)
}

如何在父组件的 count 属性中显示 cart.length 值?

父组件代码

 <q-route-tab
        count="5"
        icon="fas fa-cart-plus"
        to="/cart"
        exact
 slot="title"/>

最佳答案

根据 vue event documentation ,我们想从子组件向父组件发出一个事件。 this.$emit 方法是正确的,但它可以采用两个参数来传递数据,如下所示:

this.$emit("name", data);

因此,让我们从第一个 child 发出购物车中的商品数量:

this.$emit("cartUpdate", cart.length);

现在我们需要在父类中处理这个。我们首先需要一个 data 属性来跟踪 parent 中的 totalCartItems:

data: function () {
    return {
        totalCartItems: null
    }
}

假设您的两个代码片段都在相同父级的不同子级中,并且第一个子级(发出cartUpdate) 具有组件名称 first-child:

<first-child @cartUpdate="cartUpdate"></first-child>

每当子组件发出名为 cartUpdate 的事件(使用 @ shorthand for v-on )时,这将调用父组件中的 cartUpdate() 方法。方法很简单,只更新parent中的totalCartItems数据属性:

cartUpdate: function (totalCartItems) {
    this.totalCartItems = totalCartItems;
}

最后,让我们通过将它绑定(bind)到数据值来确保它在第二个子组件中得到更新:

<q-route-tab
        :count="totalCartItems"
        icon="fas fa-cart-plus"
        to="/cart"
        exact
 slot="title"/>

关于vue.js - 子事件发生后立即通知父组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51387328/

相关文章:

javascript - 无法分配给函数“class Template7”的只读属性 'prototype'

javascript - 本地指令 Vuejs 参数未定义

vue.js - this.$refs.name.select() 函数在 vue 中找不到

vue.js - 在 VueJS 中如何确定模板中元素的元素宽度

javascript - 如何在没有 _rowVariant 的情况下动态更改表格行的颜色?

javascript - 如何让 Vue 在 shadow dom 中工作

vue.js - 用 axios : cancel previous request when new character 搜索

javascript - Vue.js 改变 Prop

javascript - 基于 promise 的对话 vue js?

javascript - 仅当值有效时,如何通过 Vue 中的 v-model 将更改应用于输入?