如何将Vue.js中的计算道具与TypeScript一起使用?

如何将Vue.js中的计算道具与TypeScript一起使用?,typescript,vue.js,vuejs2,Typescript,Vue.js,Vuejs2,有很多关于如何使用JavaScript语言与Vue.js交互的文档,还有一些关于TypeScript的文档。问题是如果vue组件是用TypeScript编写的,那么如何定义computed道具 根据,computed是一个具有函数的对象,这些函数将根据其依赖的道具进行缓存 下面是我举的一个例子: 从“Vue”导入Vue; 从“vue属性装饰器”导入{Component}; @组件({}) 导出默认类ComputedDemo扩展Vue{ private firstName:string='John

有很多关于如何使用JavaScript语言与Vue.js交互的文档,还有一些关于TypeScript的文档。问题是如果
vue
组件是用TypeScript编写的,那么如何定义
computed
道具

根据,
computed
是一个具有函数的对象,这些函数将根据其依赖的道具进行缓存

下面是我举的一个例子:

从“Vue”导入Vue;
从“vue属性装饰器”导入{Component};
@组件({})
导出默认类ComputedDemo扩展Vue{
private firstName:string='John';
私有lastName:string='Doe';
私有计算:对象={
fullName():字符串{
返回`${this.firstName}${this.lastName}`;
},
}
}
和html:


计算机道具演示
  • 名字:{{firstName}}
  • 姓氏:{{lastName}
  • 一起:{{fullName}

第三个列表项不输出任何内容。有谁能告诉我在这种情况下如何定义
computed
。因此,您可能需要在诸如render和computed中的方法上注释返回类型

import Vue, { VNode } from 'vue'

const Component = Vue.extend({
  data () {
    return {
      msg: 'Hello'
    }
  },
  methods: {
    // need annotation due to `this` in return type
    greet (): string {
      return this.msg + ' world'
    }
  },
  computed: {
    // need annotation
    greeting(): string {
      return this.greet() + '!'
    }
  },
  // `createElement` is inferred, but `render` needs return type
  render (createElement): VNode {
    return createElement('div', this.greeting)
  }
})
如果发现类型推断或成员完成不起作用,则注释某些方法可能有助于解决这些问题。使用--noImplicitAny选项将有助于找到许多未注释的方法


您可以使用属性访问器声明计算属性。看见输入时会立即触发getter

例如:

<template>
    <div>
        <input type="text" name="Test Value" id="" v-model="text">

        <label>{{label}}</label>
    </div>

</template>

<script lang="ts">
import { Component, Vue, Watch } from "vue-property-decorator";

@Component({})
export default class About extends Vue {
    private text = "test";

    get label() {
        return this.text;
    }
}
</script>

{{label}}
从“Vue属性装饰器”导入{Component,Vue,Watch};
@组件({})
导出关于扩展Vue的默认类{
私有文本=“测试”;
获取标签(){
返回此.text;
}
}

Vue合成Api的更新

{{label}}
从“@vue/composition api”导入{defineComponent,ref,computed};
导出默认定义组件({
设置(){
常量文本=参考(“测试”);
常量标签=计算(()=>{
返回text.value;
});
返回{
文本,
标签
};
}
});

它工作正常,看起来很容易使用。浏览器中的Vue插件也将这些getter标记为计算道具。
Watch
从未在第一个示例中使用过,我是否遗漏了什么?@lurscher,你是对的,我将删除我的作品,不需要重写为基于类的组件样式。
<template>
  <div>
    <input type="text" name="Test Value" id v-model="text" />

    <label>{{label}}</label>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed } from "@vue/composition-api";

export default defineComponent({
  setup() {
    const text = ref("test");

    const label = computed(() => {
      return text.value;
    });

    return {
      text,
      label
    };
  }
});
</script>