【问题标题】:Passing Parent Function to Child Component in VueJS在VueJS中将父函数传递给子组件
【发布时间】:2016-03-27 06:40:23
【问题描述】:

我正在练习 VueJS 1.0,并且正在学习组件。 在这个example 中,有一个input 元素并且必须从API 提供coupon 或某种code。我必须验证。我有我的<coupon > 组件和when-applied 的道具。 when-applied 必须调用父函数 setCoupon 但不会。

我只收到此错误this.whenApplied is not a function

    <div id="demo" class="list-group">
        <script id="coupon-template" type="x-template">
            <input type="text" v-model="coupon" v-on:blur="whenCouponHasBeenEntered">
            <div v-text="text"></div>
        </script>
      <coupon when-applied="setCoupon"></coupon>
    </div>

这是我的app.js 文件

Vue.component('coupon', {
  template: '#coupon-template',

  props: ['whenApplied'],

  data: function() {
    return {
      coupon: '',
      invalid: false,
      text: ''
    } 
  },


  methods: {
    whenCouponHasBeenEntered: function() {
      this.validate();
    },

    validate: function() {
      if( this.coupon == 'FOOBAR') {
        this.whenApplied(this.coupon);
        return this.text = '20% OFF!!';
      }

      return this.text = 'that coupon doesn`t exists';
    }
  }
});

new Vue({
  el: '#demo',

  methods: {
    setCoupon: function(coupon) {
      alert('set coupon'+ coupon);
    }
  }
});

请有人帮忙。非常感谢您的建议。

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    你应该bind该属性:

    <coupon v-bind:when-applied="setCoupon"></coupon>
    

    或者你可以使用v-bind的简写语法:

    <coupon :when-applied="setCoupon"></coupon>
    

    阅读更多关于propshere的信息。

    【讨论】:

      猜你喜欢
      • 2021-12-27
      • 2017-01-07
      • 2020-09-16
      • 2019-01-07
      • 1970-01-01
      • 2020-08-06
      • 2021-04-22
      相关资源
      最近更新 更多