如何在Vue.js中使用带有打字稿的计算道具

Lev*_*hev 16 typescript vue.js vuejs2

有很多文档说明如何使用javascript语言与Vue.js进行交互,以及一些关于typescript的内容.问题是如果computedvuecomponent上编写道具,如何在组件中定义道具.根据官方示例 computed,具有将基于其依赖道具缓存的函数的对象.这是我做的一个例子:

import Vue from 'vue';
import { Component } from "vue-property-decorator";

@Component({})
export default class ComputedDemo extends Vue {
    private firstName: string = 'John';
    private lastName: string = 'Doe';
    private computed: object = {
        fullName(): string {
            return `${this.firstName} ${this.lastName}`;
        },
    }
}
Run Code Online (Sandbox Code Playgroud)

和HTML:

<div>
    <h1>Computed props ts demo</h1>
    <ul>
        <li>First name: {{firstName}}</li>
        <li>Last name: {{lastName}}</li>
        <li>Together: {{fullName}}</li>
    </ul>
</div>
Run Code Online (Sandbox Code Playgroud)

第三个列表项没有输出.有谁能告诉我computed在这种情况下如何定义,拜托?

Jer*_*ers 28

您可以使用属性访问器来声明计算属性(https://github.com/vuejs/vue-class-component).只要输入输入,就会触发吸气剂.见例子

<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>
Run Code Online (Sandbox Code Playgroud)


Bad*_*dgy 18

由于 Vue 声明文件的循环性质,TypeScript 可能难以推断某些方法的类型。出于这个原因,您可能需要在渲染和计算等方法上注释返回类型。

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)
  }
})
Run Code Online (Sandbox Code Playgroud)

如果您发现类型推断或成员补全不起作用,注释某些方法可能有助于解决这些问题。使用 --noImplicitAny 选项将有助于找到许多这些未注释的方法。

更多信息