使用当前 vue 组件的方法作为默认 prop 值

Mar*_*her 6 javascript vue.js vue-component vuejs2

我将把函数作为属性传递给 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!");
    }
  }
});
Run Code Online (Sandbox Code Playgroud)
#app {
  margin: 20px;
}

.holder > button {
  margin: 10px;
  padding: 5px;
  font-size: 1.1em;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

myn*_*ynd 6

来自 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。


ski*_*tle 5

这有效,但它是一整套扳手:

action: {
  required: false,
  default () { 
    return () => this.innerMethod();
  },
},
Run Code Online (Sandbox Code Playgroud)

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

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

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

invokeAction () {
  if (this.action) {
    this.action();
  } else {
    this.innerMethod();
  }
}
Run Code Online (Sandbox Code Playgroud)