【问题标题】:How to decorate typescript vue class component with an imported method?如何用导入的方法装饰 typescript vue 类组件?
【发布时间】:2019-09-04 20:53:44
【问题描述】:

我最近开始使用带有 typescript 的 vue 类组件,但找不到用导入的实用程序方法装饰组件类的方法。我正在使用nuxt-property-decorator 来装饰我的组件。

我已经尝试添加方法,就像我在没有打字稿的 vue 组件中那样:

import doSomething from './somewhere';

<script>
    export default {
        methods: {
            doSomething,// I'd do this without typescript, works as expected
        },
    }
</script>

<script lang="ts">
    import Vue from 'vue';
    import {Component} from 'nuxt-property-decorator';
    import doSomething from './somewhere';

    @Component
    export default class MyCustomClass extends Vue {
        doSomething, // Doesn't, "Property or method doSomething is not defined on the instance but referenced during render..."

        hacky() {
            return doSomething(); // I guess I could do it this way, but this looks like a very hacky way
        }
    }
</script>

【问题讨论】:

    标签: typescript vuejs2 nuxt.js


    【解决方案1】:

    你所要做的就是:

    doSomething = doSomething
    

    所有其他方法都在哪里。

    【讨论】:

      【解决方案2】:

      解决这个问题的方法是简单地使用@Component 来装饰组件:

      <script lang="ts">
          @Component({
              methods: {
                  preventContextMenu,
              },
          })
          export default class MyCustomClass extends Vue {
              ...
          }
      </script>
      

      【讨论】:

        【解决方案3】:

        在我使用vue-property-decorator 之前。据我所知,nuxt-property decorator 就是基于它。

        不确定这是否是您要查找的内容,但如果您想在组件初始化上运行某些东西,您可以在组件内使用mounted。这是生命周期钩子

        例子:

                import doSomething from './somewhere';
        
                <script>
                    export default {
                        methods: {
                            doSomething,// I'd do this without typescript, works as expected
                        },
                    }
                </script>
        
                <script lang="ts">
                    import Vue from 'vue';
                    import {Component} from 'nuxt-property-decorator';
                    import doSomething from './somewhere';
        
                    @Component
                    export default class MyCustomClass extends Vue {
        
                        public mounted(){
                          doSomething...
                          // everything in this method  will be triggered on component load
                        }
                    }
                </script>
        

        【讨论】:

        • 你是对的——nuxt-property-decorator 基于vue-property-decorator,但你没有正确理解我的问题。我不想使用组件生命周期挂钩,我想在我的组件中使用导入的方法 - doSomething 是我从某些 es6 模块导入的方法,我的问题是我找不到使用它的方法导入的方法,对不起我的英语能力差。
        猜你喜欢
        • 2021-01-23
        • 2021-01-31
        • 2019-10-22
        • 2021-03-01
        • 1970-01-01
        • 2019-06-11
        • 2019-02-03
        相关资源
        最近更新 更多