【问题标题】:vue class component inheritance, method from base class "is not a function"vue类组件继承,来自基类的方法“不是函数”
【发布时间】:2020-11-10 05:33:24
【问题描述】:

我正在尝试制作class inheritance 以避免在defining stories for storybook 时出现代码冗余,因为我有一堆场景(故事)来涵盖更少/更多的数据相似性。我正在使用带有 vue-property-decorator 的 vue-class-component 方法来定义组件。

这是一个例子:

//myStory.stories.ts file
import Vue from 'vue'
import {Component} from 'vue-property-decorator'
import {store} from 'path/to/stores'
import Vuex from 'vuex'

const BaseOptions = {
  components: {Component1, Component2},
  template: MyTemplate,
  store: new Vuex.Store<IRootState>(store)
}

class BaseClass extends Vue {
  public method1() {
    console.log("call from method 1")
  }
  // I want to customize many methods here in BaseClass: method2, method3, etc
}

// Story book page
export default {
  title: 'My/Page',
  // Our exports that end in "Data" are not stories.
  excludeStories: /.*Data$/,
}

// Defining storybook stories:
export const ScenarioOne = () => (
  @Component<any>(
    {
      ...BaseOptions,
      mounted() {
        this.method1()
      },
    }
  )
  class CurrentClass extends BaseClass {} // This isn't working >> error: _this4.method1 is not a function
)


export const ScenarioTwo = () => (
  @Component<any>(
    {
      ...BaseOptions,
      mounted() {
        this.method1()
      },
    }
  )
  class CurrentClass extends BaseClass {
    // If I redefine the method1(), it's working
    public method1() {
       console.log("call from method 1 (redefined)")
    }
  }
)

为什么我的scenarioOne 不能调用method1()scenarioTwo 可以?

【问题讨论】:

    标签: typescript inheritance vuejs2 storybook vue-class-components


    【解决方案1】:

    您还必须将基类定义为@Component({}),以及继承链中的所有类,所以:

    import Vue from "vue";
    import Component from "vue-class-component";
    
    @Component({})
    class BaseClass extends Vue {
    }
    
    @Component({})
    class SubClass extends BaseClass {
    }
    

    【讨论】:

      猜你喜欢
      • 2014-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-16
      • 2014-12-23
      • 2016-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多