Ref Composition API Vue

huangapple go评论63阅读模式
英文:

Typing the Ref Composition API Vue

问题

如何正确将我的 Ref firstName 类型设置为字符串?有两个错误被下划线标出,一个在模板中 - {{ firstName }},另一个在脚本中 - const firstName = ref('') as String。我认为这与类型有关,对于 Ref,我假设它正在正常工作。

英文:

how could I type correctly my Ref firstName as string? There are 2 errors underlined, in the template - {{ firstName }}, and in the script - const firstName = ref('') as String. I suppose it has to do with the typing, for the Ref I assume is working correctly.

<template>
  </div> -->
  <v-sheet >
      <v-form fast-fail @submit.prevent>
        <v-text-field
          label="First name"
        >{{ firstName }}</v-text-field>
      </v-form>
    </v-sheet>
</template>
<script lang="ts">
import { ref } from 'vue'
export default {
  setup() {
    const firstName = ref('') as String
  },
  }
</script>

答案1

得分: 0

以下是翻译好的代码部分:

<script> 版本

<script lang="ts">
import { ref } from 'vue'
export default {
  setup() {
    const firstName = ref<string>('Alexander')
    return { firstName }
  }
}
</script>

<template>
  {{ firstName }}
</template>

<script setup> 版本

<script setup lang="ts">
import { ref } from 'vue'
const firstName = ref<string>('Alexander')
</script>

<template>
  {{ firstName }}
</template>

SFC Playground

英文:

Compilation from both comments

<script> version

<script lang="ts">
import { ref } from 'vue'
export default {
  setup() {
    const firstName = ref<string>('Alexander')
    return {firstName}
  }
}
</script>

<template>
  {{ firstName }}
</template>

<script setup> version

<script setup lang="ts">
import { ref } from 'vue'
const firstName = ref<string>('Alexander')
</script>

<template>
  {{ firstName }}
</template>

SFC Playground

huangapple
  • 本文由 发表于 2023年2月18日 20:58:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75493490.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定