Vue3 typescript composition API stylebinding with async method get error

Viewed 539

I used nexttick with async method to update dom element.

Cannot return correct style type.

And get error 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>

enter image description here

2 Answers

What you want is not possible - Methods

Methods called from a template should not have any side effects, such as changing data or triggering asynchronous processes. If you find yourself tempted to do that you should probably use a lifecycle hook instead.

Since getHeight is an async function, it automatically returns a Promise. The style binding only accepts StyleValue objects (i.e., those with CSS style properties), so the Promise causes the error you observed.

However, there's no need for async/await in your example, and removing it 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}
  }
}
Related