首页 > 解决方案 > Vue.js 方法未定义

问题描述

这是方法的一些问题,我的组件无法访问方法。我是否需要将诸如 prop 之类的方法传递给组件?

这是我的html:

<guests v-bind="guests"></guests>

这是我的 js 文件中的组件

var guestsComponent = Vue.component("guests", {
  props: ['adultCount', 'childCount'],
  template: `
    <div class="guests-total">
      <div>
      <a @click="decrementAdult"></a>
      <a @click="incrementAdult"></a>
      <input type="text" placeholder="adults"/> {{adultCount}}
      </div>
    </div>
  `
});

在同一个 js 文件中,我的 vue init 和方法

var app = new Vue({
  el: "#search",
  components: {
    "guests": guestsComponent
  },
  data() {
    return {
      guests: {
        adultCount: 0,
        childCount: 0
      }
    };
  },
  methods: {
    decrementAdult() {
      this.guests.adultCount++
    },
    incrementAdult() {
      this.guests.adultCount--
    }
  }
});

当我使用道具时,我可以毫无问题地访问数据,但我不知道如何传递道具之类的方法,或者这是需要的?

这是控制台上的错误:

ReferenceError: decrementAdult is not defined
    at o.eval (eval at xa (vue.min.js:NaN), <anonymous>:3:88)
    at o.fn._render (vue.min.js?f6b5:6)
    at o.eval (vue.min.js?f6b5:6)
    at St.get (vue.min.js?f6b5:6)
    at new St (vue.min.js?f6b5:6)
    at o.hn.$mount (vue.min.js?f6b5:6)
    at o.hn.$mount (vue.min.js?f6b5:6)
    at init (vue.min.js?f6b5:6)
    at eval (vue.min.js?f6b5:6)
    at b (vue.min.js?f6b5:6)

标签: javascriptvue.jsvuejs2vue-component

解决方案


Since the click events are done in the child component guests you should emit an event to the parent component and handle it there like :

    ....
    <a @click="$emit('decrement-adult')"></a>
     ...

in the parent component do :

   <guests v-bind="guests" @decrement-adult="decrementAdult"></guests>

推荐阅读