【问题标题】:Vue.js passing functions to props not workingVue.js 将函数传递给道具不起作用
【发布时间】:2015-09-16 21:21:51
【问题描述】:

我有一个问题,将函数传递给组件没有按照文档中指定的方式工作。

这是在我的 app.js 中

methods: {
    updateAnswer: function(question) {
        console.log('question: '+question);
    }
}

这是在我的 html 文件中:

<multiplechoice class="question counterIncrement counterShow active" id="q2" whenanswered="{{ updateAnswer('1') }}"></multiplechoice>

这是在我的 components.js 文件中:

props: [
    'whenanswered'
],

ready: function() {
    this.whenanswered();
},

我已经试过了:

props: [
    { name: 'whenanswered', type: Function}
];

但还是没有运气。

当我加载页面时,这是在我的控制台中:

Uncaught TypeError: this.whenanswered is not a function

任何帮助将不胜感激:)

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    你可以这样做:

    <multiplechoice class="question counterIncrement counterShow active" id="q2" :whenanswered="updateAnswer('1')"></multiplechoice>
    

    如果没有':'(与 v-bind 相同),就像您所做的那样,只会发送一个字符串而不是评估。即使是那些{{ }}

    但请记住,您的 updateAnswerfunction 应该返回一个函数。由于您的道具将执行updateAnswer('1'),而您的multiplechoice实际上希望有一个函数会在需要时执行。

    methods: {
      whenanswered: function(question) { // or whenanswered (question) { for ES6 
        return function () { ... } // or () => {...} for ES6
      }
    }
    

    【讨论】:

      【解决方案2】:

      小提琴会有所帮助,但基本上,你需要:

      methods: {
          whenanswered: function(question) {
              ...
          }
      }
      

      如果你想调用那个函数。 prop 只是一个字符串,而不是一个函数。

      例子:

      <div id="app">
          Loading...
          <data-table on-load="{{onChildLoaded}}"></data-table>
      </div>
      
      new Vue({
        el: "#app",
          methods: {
              onChildLoaded: function (msg) {
                  console.log(msg);
              }
          },
          components: {
              'data-table': {
                  template: 'Loaded',    
                  props: ['onLoad'],
                  ready: function () {
                      this.onLoad('the child has now finished loading!')
                  }
              }
          }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-17
        • 2018-05-31
        • 1970-01-01
        • 2021-07-30
        • 1970-01-01
        • 2019-07-03
        • 2019-09-21
        • 1970-01-01
        相关资源
        最近更新 更多