Home > Software design >  what's the best way to initialize reactive variable without value in vue3 with typescript?
what's the best way to initialize reactive variable without value in vue3 with typescript?

Time:06-10

I would like to initialize a reactive variable without a value. I tried:

const workspaceReact = reactive(null) // wrong! it is seems value null can not being passed to reactive()

So I tried the following code, and it seems to work:

let workspaceReact:UnwrapRef<ToolboxInfo>;
workspaceReact = reactive(toolbox)

but I feel it's too complicated. Is there any better way to do that?

CodePudding user response:

That is not possible. A reactive needs to extend an object https://vuejs.org/api/reactivity-core.html#reactive

reactive()

Returns a reactive proxy of the object.

Type

function reactive<T extends object>(target: T): UnwrapNestedRefs<T>

Your options are:

  • Initialize with an empty object {}
  • use a ref

CodePudding user response:

One solution is to switch from reactive to a ref, and use the Reactivity Transform in <script setup>, which automatically unwraps refs.

To use it, replace ref/computed with $ref/$computed (no import needed):

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

type ToolboxInfo = {
  name: string
  id: string
  counter: number
}
                                  
  • Related