相关疑难解决方法(0)

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

我将把函数作为属性传递给 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)

javascript vue.js vue-component vuejs2

6
推荐指数
2
解决办法
3176
查看次数

标签 统计

javascript ×1

vue-component ×1

vue.js ×1

vuejs2 ×1