如何在Vue Typescript中访问computed的props?

toiithl6  于 2023-04-21  发布在  Vue.js
关注(0)|答案(1)|浏览(166)

我想为我的计算器获取 prop 数据。这是代码

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  props: {
    color: String,
    shape: String,
  },
  computed: {
    theme(): string {
      const args: string[] = props.color.split('-') //Cannot find name 'props'
      let var_1:string = args[0]

      return var_1
    }  
  }
})
</script>

我试着用“这个.颜色”,它也不起作用

bmvo0sr5

bmvo0sr51#

通过this访问是正确的,但Typescript会抱怨,因为this.color可能未定义。您可以将属性设置为required,或者让计算的theme处理undefined。
下面是所需的颜色:

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  props: {
    color: {required: true, type: String}, // <--- make color required
    shape: String,
  },
  computed: {
    theme(): string {
      const args: string[] = this.color.split('-') // <--- access with `this`
      let var_1:string = args[0]

      return var_1
    }  
  }
})
</script>

或者你可以用类似这样的方法来处理未定义的值:

theme(): string {
      return this.color?.split('-')[0] ?? ''
    }

相关问题