【问题标题】:Use current vue component's method as default prop value使用当前 vue 组件的方法作为默认 prop 值
【发布时间】:2019-12-10 07:04:48
【问题描述】:

我要将函数作为属性传递给 Vue 组件。让它成为函数必须由@click 调用。但由于某些原因,我想保留组件的默认行为。默认行为并不像我想要的那么简单,我将使用method 作为默认函数。因为默认行为需要来自组件状态的数据(道具、数据、其他方法等)。

有办法吗?

我已附上示例。预期行为:

按钮works fine 应该产生警报You are welcome!
按钮 nope 应该产生警报 You are welcome as well! 但什么也不做。

Vue.component('welcome-component', {
  template: '#welcome-component',
  props: {
    name: {
      type: String,
      required: true,
    },
    action: {
      type: Function,
      required: false,
      default: () => { this.innerMethod() },
    },
  },
  methods: {
    innerMethod() {
      alert("You are welcome as well!");
    }
  }
});


var app = new Vue({
  el: "#app",
  methods: {
    externalMethod() {
      alert("You are welcome!");
    }
  }
});
#app {
  margin: 20px;
}

.holder > button {
  margin: 10px;
  padding: 5px;
  font-size: 1.1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <welcome-component name="works fine" :action="externalMethod"></welcome-component>
  <welcome-component name="nope"></welcome-component>
</div>


<script id='welcome-component' type='x-template'>
  <div class="holder">
    <button @click="action">{{ name }}</button>
  </div>
</script>

【问题讨论】:

  • default: () =&gt; { 如何在不在范围内的箭头函数内引用this?还是它在 Vue 编译器的范围内神奇地存在?还是我错过了什么?
  • @JamesHarrington 完全正确。这是问题
  • 啊@MartenCatcher 感谢您的澄清。 :)

标签: javascript vue.js vuejs2 vue-component


【解决方案1】:

来自 vue 文档:

"Note that props are validated before a component instance is created, so instance properties (e.g. data, computed, etc) will not be available inside default or validator functions."(https://vuejs.org/v2/guide/components-props.html)

因此,引用innerMethod 是组件功能尚不可用的情况之一。

想法:如果拥有这种功能对您来说至关重要,您可以在以后的生命周期挂钩(如创建、挂载等)中检查action 的类型是否为function。如果不是函数(即不通过 prop 传递),手动分配 innerMethod。

【讨论】:

    【解决方案2】:

    这可行,但它是一包扳手:

    action: {
      required: false,
      default () { 
        return () => this.innerMethod();
      },
    },
    

    我不得不删除type: Function。通常当default 是一个函数时,它将被调用以返回适当的默认值。但是,如果 prop 有 type: Function 它只会将该函数视为默认值。在这种情况下,这是有问题的,因为我们丢失了 this 绑定。

    需要内部箭头函数来解决调用default函数时方法不可用的问题。

    如果可能的话,我建议放弃使用default,而是在需要调用时应用“默认”。因此,与其直接在click 处理程序中调用action,不如调用一个名为invokeAction 的方法,如下所示:

    invokeAction () {
      if (this.action) {
        this.action();
      } else {
        this.innerMethod();
      }
    }
    

    【讨论】:

    • 它有效,谢谢。但我认为我必须改变我的应用程序的逻辑以使其更加标准。
    猜你喜欢
    • 1970-01-01
    • 2021-04-24
    • 2020-08-22
    • 2011-08-08
    • 2020-05-27
    • 1970-01-01
    • 2012-10-23
    • 2020-12-07
    • 2019-12-19
    相关资源
    最近更新 更多