代码之家  ›  专栏  ›  技术社区  ›  Suhail Gupta

将值从组件传递到父实例

  •  0
  • Suhail Gupta  · 技术社区  · 8 年前

    我有一个名为 cartComponent 具有数据属性 cartCount 每当一个新项目添加到购物车时,该值就会增加。

    我需要使用该值来更新模板中的值,该值不是组件的一部分。这可能吗?

    以下是我的父Vue实例的脚本:

    new Vue({
      el: "#cart-app",
      components: {
        cart: cartComponent
      },
      data: {
        searchQuery: '',
        appliedFilters: ['Day 1'],
        purchaseData: json,
        cCount: 0 // CARTCOUNT; NEEDS TO BE UPDATED FROM COMPONENT
      }
    });
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   tony19 thanksd    3 年前

    这是使用 .sync modifier .

    根据文件:


    .同步 cCount 在模板中绑定的属性(假设组件具有 帐户

    <cart :c-count.sync="cCount"></cart>
    

    update:cCount 计数递增时的事件:

    methods: {
      incrementCount() {
        this.cartCount++;
        this.$emit('update:cCount', this.cartCount);
      }
    }
    

    帐户 cartCount 所有物

    Here's a working fiddle.


    此功能从Vue 2.3.0版开始提供,但如果您使用的是早期版本,这将为您提供相同的功能:

    <cart :c-count="cCount" @update:foo="val => cCount = val"></cart>
    

    这是因为 <comp :foo.sync="bar"></comp>

    <comp :foo="bar" @update:foo="val => bar = val"></comp>
    
    推荐文章