在VueJS中将父函数传递给子组件

JavaScript

An

2020-03-12

我正在VueJS 1.0中进行练习,并且正在学习有关Components的知识。在此example,有一个input元素必须从API 提供coupon或某种形式code我必须验证。我有我的<coupon >组成部分,并且具有的道具when-appliedwhen-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);
    }
  }
});

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

第1191篇《在VueJS中将父函数传递给子组件》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
路在何方 2020.03.12

您应该bind具有以下属性:

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

或者您可以将简写语法用于v-bind

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

props 此处了解更多信息

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android