【问题标题】:How to know from which child is emitting an event in vue.js 3?如何知道 vue.js 3 中哪个孩子发出事件?
【发布时间】:2021-07-03 15:57:57
【问题描述】:

如果我有一个组件:

<product-display 
  :premium="premium" 
  :cart="cart" 
  @add-to-cart='updateCart' 
  @remove-from-cart='removeById'>
</product-display>

用这两种方法:

 methods: {
        removeFromCart() {
            this.$emit('remove-from-cart', this.variants[this.selectedVariant].id)
        },
        addToCart() {
            this.$emit('add-to-cart', this.variants[this.selectedVariant].id)
        },

而父级有这些方法:

 methods: {
        updateCart (id) {
            this.cart.push(id)
        },
        removeById(id) {
            const index = this.cart.indexOf(id)
                if (index > -1) {
                    this.cart.splice(index, 1)
                }
        }
    }

有没有办法从父级中删除一个方法并仅使用 updateCart(id) 知道从哪个子级发出事件?

所以在 HTML 中你最终会得到:

 @add-to-cart='updateCart' 
 @remove-from-cart='updateCart'

【问题讨论】:

    标签: javascript html events dom-events vuejs3


    【解决方案1】:

    您可以通过几种不同的方式做到这一点。我的首选是这样的:

    // Component.vue
    updateCart(action) {
      this.$emit('update-cart', {
        id: this.variants[this.selectedVariant].id), action
    }
    
    //Parent.vue
    @update-cart='updateCart'
    
    methods: {
      updateCard({id, action}) {
        if (action == 'add') {
          return this.cart.push(id);
        }
        this.card = this.card.filter(x => x != id);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多