How can I best declare a reactive variable without a value in Vue 3 using TypeScript?

Is there a way to initialize a reactive variable without assigning it a value initially? After trying various methods, I found that using null as the initial value doesn't seem to work:

const workspaceReact = reactive(null) // incorrect! Cannot pass null as value to reactive()

After some experimentation, I came up with the following solution which seems to be functioning correctly:

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

However, I feel like this approach might be overly complex. Is there a simpler or more efficient way to achieve this?

Answer №1

If you're looking for a solution, consider transitioning from using reactive to utilizing a ref. By incorporating the Reactivity Transform within the <script setup>, you can automatically unwrap refs.

To implement this change, simply substitute ref/computed with $ref/$computed (without requiring an import):

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

type ToolboxInfo = {
  name: string
  id: string
  counter: number
}
                       👇
let workspaceReact = $ref<ToolboxInfo | null>(null)
let msg = $computed(() => `Hello ${workspaceReact?.name}!`)
const onClick = () => workspaceReact!!.counter++

onMounted(() => {
  workspaceReact = {
    id: 'my id',
    name: 'my toolbox',
    counter: 0,
  }
})
</script>

Check out the demo here

Note: Please be aware that as of now (

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cabcbfaf8af9e4f8e4f9fd">[email protected]</a>
), this feature is considered experimental:

⚠️ Experimental Feature

The Reactivity Transform remains an experimental aspect at present. It is not enabled by default and requires explicit opt-in. Furthermore, there may be further modifications before its official release. For updates, monitor the proposal and discussion on GitHub.

Answer №2

It is not feasible. A reactive requires extension of an object https://vuejs.org/api/reactivity-core.html#reactive

reactive()

Generates a reactive proxy for the specified object.

Type

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

You have the following options:

  • Start with an empty object {}
  • utilize a ref

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a TypeError in Laravel VueJS testing: Unable to locate _vm._ssrEscape function

I have been trying to set up Mocha tests for Laravel 7 Vue Components by combining different tutorials. Initially, I was able to run a basic test successfully: expect(0).toBe(0); However, when attempting to mount a component, I encountered the following ...

Displaying a certain div when clicked within a loop using Vue.js and Laravel

I am currently facing an issue with displaying a hidden div upon click. The problem arises when using a loop to dynamically generate all the divs. Whenever I click the button, it shows all the divs instead of just one specific div on each click. I attempte ...

A guide to mocking Prisma using Jest mock functionality

Utilizing prisma for database interactions and eager to implement jest-mock to simulate the findMany call. https://jestjs.io/docs/jest-object#jestmockedtitem-t-deep--false brands.test.ts import { PrismaService } from "@services/mysql.service"; i ...

Vue: Applying a specific class to a single element in a v-for loop

When using a v-for loop to display a list of items, I have implemented a function triggered by @click that deletes the item. However, I want to add a temporary background color change upon clicking to indicate to the user that the deletion is in progress ...

Issues with Vuetify not recognizing style adjustments

Trying to modify the design so that buttons display text with capital letters instead of all uppercase. My version of Vue is 3.5.5 I have included src/stylus/main.styl $button-text-transform = 'capitalize' @require '~vuetify/src/stylus/ap ...

What are the steps to releasing and utilizing a Node package in Laravel 5?

Recently, I've started integrating Vuejs into my existing laravel application. Although it's a new experience for me, I'm excited to learn more about it. One feature that caught my eye is this component: A multiselect with search-autocomple ...

What are the steps to integrate MaterializeCss into Vue.js?

I prefer not to utilize Vue-Material or Vuetify. My choice is Materialize. Here's what I do: npm install materialize-css@next In my main.js file, where I define my new Vue App, I import Materialize like this: import 'materialize-css' Th ...

Setting checkbox values using patchValue in Angular programming

I'm facing an issue with reusing my create-form to edit the form values. The checkbox works fine when creating a form, but when I try to edit the form, the values don't get updated on the checkbox. Below is the code snippet that I have been worki ...

New options for outdated Webpack i18n plugin and loader

I am currently working on a TypeScript project that requires loading translations from individual .json files assigned to each country. For instance, we would have separate language files like en.json, es.json. The goal is to be able to access these trans ...

Strange behavior of the .hasOwnProperty method

When attempting to instantiate Typescript objects from JSON data received over HTTP, I began considering using the for..in loop along with .hasOwnProperty(): class User { private name: string; private age: number; constructor(data: JSON) { ...

Guide to integrating a Vue.js project with Yocto platform

I am looking to integrate a Vue.js project into a Yocto image using devtool to create the recipe. 'devtool add <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="44232d3004232d302c31266a272b29">[email protected]</a& ...

Changing global properties in VueCli

Recently, I integrated a component library into my Vue 3 project. All instances of the component require the same styles. Instead of manually adjusting each instance's props, I opted to utilize a global property: app.config.globalProperties.$tooltipS ...

Modify the ShortDate formatting from "2020/06/01" to "2020-06-01"

I am looking to modify the shortDate format in my template file. Currently, when I try to change it to use "-", it still displays the date with "/". What I actually want is for the output to be formatted as yyyy-MM-dd. <ngx-datatable-column name="C ...

Leveraging global variables within Vuex state management strategy

I have successfully added custom global variables into Vue by injecting them. Here is the code snippet: export default function (props, inject) { inject('models', { register(name) { const model = require(`@/models/${name}. ...

Developing various VueJS TypeScript projects utilizing a shared library

In the process of developing two VueJS applications using TypeScript, I have created one for public use and another as an admin tool exclusively for my own use. Both applications are being built and tested using vue-cli with a simple npm run serve command. ...

How can I retrieve server-side data in the client-side using NodeJs (connecting to MySql) with Vue CRUD?

Currently, I am delving deeper into Vue and to make the learning process more engaging, I have established a connection to my MySql-DB using nodeJS. Following a detailed tutorial (), I successfully implemented a Login system. Now, my goal is to retrieve d ...

Tips for effectively sharing content on social media from your Vuejs application

I have been using the vue-social-sharing library to enable social media sharing on my website, and overall it's been working well. However, I am facing a problem where when I click the Facebook share button, it doesn't share the title, descriptio ...

Tips for customizing the main select all checkbox in Material-UI React data grid

Utilizing a data grid with multiple selection in Material UI React, I have styled the headings with a dark background color and light text color. To maintain consistency, I also want to apply the same styling to the select all checkbox at the top. Althou ...

Experiencing an issue with my Angular 6.1.0 setup, using angular-cli 7 and primeng 7 - specifically encountering the error message "Initializers are not allowed in ambient context."

Issue encountered in the primeng package: While examining node_modules/primeng/components/picklist/picklist.d.ts, errors were found at line numbers 65 and 66. I have investigated the primeng package further. primeng/components/picklist/picklist.d.ts l ...

Capturing content from an HTML node and integrating it into VueJS data

<tasks> @foreach ($task as $tasks) <task>{{ $task->name }} [{{ $task->completed }}]</task> @endforeach </tasks> This snippet shows how I display a list of tasks from the database. Here is my Vue component setu ...