【问题标题】:vue3 class component access propsvue3 类组件访问道具
【发布时间】:2021-06-25 16:34:11
【问题描述】:

我在 typescript 中使用带有类组件的 vue3 我的类看起来像:

import {Options, Vue} from "vue-class-component";

@Options({
  props: {
    result: Object
  }
})


export default class imageResult extends Vue {
  currentImage = 0;

  getSlides(){
    console.log('result',this.$props.result); // not working
    console.log('result',this.result); // not working too
  }

我的问题是,我如何在班级中访问和使用该属性?

this.resultthis.$props.result 都会给我一个错误。

有人可以帮助我吗? 提前致谢

【问题讨论】:

    标签: vue.js vuejs3 vue-class-components


    【解决方案1】:

    我对您的建议是遵循使用类组件在 vue 中使用 Typescript 的文档:enter link description here

    为了修复您的代码,我认为这应该可行:

    import {Vue} from "vue-class-component";
    import {Component} from "vue-class-component";
    
    // Define the props by using Vue's canonical way.
    const ImageProps = Vue.extend({
      props: {
        result: Object
      }
    })
    
    // Use defined props by extending GreetingProps.
    @Component
    export default class ImageResult extends ImageProps {
      get result(): string {
        console.log(this.result);
        // this.result will be typed
        return this.result;
      }
    }
    

    【讨论】:

    • 这仅适用于 Vue 2。Vue 3 的 API 已更改。
    • 你查看过 vue 官方文档中的 typescript 组件吗?我只是关注了您正在使用的 vue-class-component 库。使用官方 vue 3 核心更直接:v3.vuejs.org/guide/typescript-support.html#annotating-props
    • 那些文档是指 Vue 本身的 Options API。但是 OP 将 vue-class-component 与 Vue 3 一起使用。这个问题与使用该库有关。
    • 感谢您的反馈!但正如托尼所说,这是针对 vue2 的。我正在寻找最新版本 3
    【解决方案2】:

    迟到的答案,但也许它会在未来帮助某人。 使用 vu3 和 typescript 为我工作

    <script lang="ts"> 
    import { Vue, prop } from "vue-class-component";
    
    export class Props {
      result = prop<string>({ required: true });
    }
    
    export default class Foo extends Vue.with(Props) {
      test(): void {
        console.log(this.result);
      }
    }
    </script>
    

    【讨论】:

      猜你喜欢
      • 2021-05-22
      • 2021-03-05
      • 2020-05-04
      • 2021-07-27
      • 2021-09-15
      • 1970-01-01
      • 2021-01-24
      • 2022-11-24
      • 1970-01-01
      相关资源
      最近更新 更多