【问题标题】:Vue3 typescript composition API stylebinding with async method get errorVue3 typescript composition API stylebinding with async method get error
【发布时间】:2021-07-14 09:54:08
【问题描述】:

我使用带有异步方法的 nexttick 来更新 dom 元素。

无法返回正确的样式类型。

然后得到错误error TS2322: Type 'Promise<{ maxHeight: string; }>' is not assignable to type 'StyleValue | undefined'. Type 'Promise<{ maxHeight: string; }>' is missing the following properties from type 'StyleValue[]': length, pop, push, concat, and 28 more.

<template>
  <div :style="getHeight(i)" class="demo" v-for="i in [1,2]">Hi</div>
</template>

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

export default {
  setup() {
    const getHeight = async (i: number) => {
      await nextTick()
      return {maxHeight: '12px'}
    };
    return {getHeight}
  }
}

</script>

<style>
.demo {
  border: 1px solid red;
}
</style>

【问题讨论】:

    标签: typescript vue.js vuejs3


    【解决方案1】:

    你想要的都是不可能的-Methods

    从模板调用的方法不应有任何副作用,例如更改数据或触发异步进程。如果您发现自己很想这样做,您可能应该使用生命周期挂钩。

    【讨论】:

      【解决方案2】:

      由于getHeight 是一个async 函数,它会自动返回一个Promisestyle binding 仅接受 StyleValue 对象(即具有 CSS 样式属性的对象),因此 Promise 会导致您观察到的错误。

      但是,您的示例中不需要async/await,并将其删除resolves the issue

      export default {
        setup() {
          //const getHeight = async (i: number) => {
          //  await nextTick()
          //  return {maxHeight: '12px'}
          //};
      
          const getHeight = (i: number) => {
            return {maxHeight: '12px'}
          };
          return {getHeight}
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-15
        • 2022-12-02
        • 2021-12-11
        • 1970-01-01
        • 1970-01-01
        • 2022-01-25
        • 2021-06-08
        • 1970-01-01
        相关资源
        最近更新 更多