Vue.js: Using variable aliases and handling null checks

Any suggestions on using a shorter name than "store.selectedNode.displayName" in my components?

Instead of:

<script setup lang="ts">
import { useStore } from '@/util/store'
const store = useStore()
</script>

<template>
    <div v-if="store.selectedNode != null">
    <input v-model="store.selectedNode.displayName">
    <input v-model="store.selectedNode.browseName">

I would prefer:

<script setup lang="ts">
import { useStore } from '@/util/store'
const store = useStore()
assert(store.selectedNode)
const node = reactive(store.selectedNode)
</script>

<template>
    <div>
    <input v-model="node.displayName">
    <input v-model="node.browseName">

However, assert doesn't seem to work inside tags here - compiler still complains that store.selectedNode might be null. Is there a better way?

Answer №1

store.selectedNode is reactive by default. If you need to ensure it is not null, use the ! non-null assertion operator. As long as selectedNode references the same object throughout the component's lifecycle, you can do:

assert(store.selectedNode)
const { browseName, displayName } = toRefs(store.selectedNode!);

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

Is it acceptable to manipulate the prevState parameter of the setState function as mutable?

It is commonly known that directly modifying this.state is not recommended, and instead setState should be used. Following this logic, I assumed that prevState should also be treated as immutable, and setState should always involve creating a new object i ...

How to set default props in Vue Select component?

I have been utilizing the vue-multiselect plugin from this website: Given that I plan to use it frequently, I am interested in establishing some default props. For instance, my aim is to have the selectLabel prop set as an empty string and possibly con ...

When multiple input fields with an iterative design are using the same onChange() function, the specific event.target.values for each input

I'm in the process of developing a dynamic select button that adjusts based on the information entered into the iterative input fields I've set up. These input fields all utilize the same onChange() function. for (let i = 0; i < selectCount; i ...

Utilizing an Angular framework to access external JavaScript libraries when the document is fully

I'm incorporating a third-party JavaScript library into my .NET Core ASP Angular application. This library executes its functionality within the $(document).ready method. However, I've encountered an issue where the library's logic isn' ...

Understanding the return parameter "typeof SomeClass" in TypeScript

typeof in JavaScript returns a string. The TypeScript typings for Sequelize include return types of typeof Model. What does this mean and what is its purpose? I have looked through the documentation but could not find an explanation. Link to Sequelize Typ ...

Converting a Typescript project into a Node package: A step-by-step guide

I'm currently dealing with an older typescript project that has numerous functions and interfaces spread out across multiple files. Other packages that depend on these exports are directly linked to the file in the directory. My goal is to transition ...

Obtaining JSON and PHP data simultaneously within a function

I have incorporated the laravel-searchable package developed by Spatie to enhance search functionalities within my Laravel application. Inside my SearchController.php file, I have the following code snippet: public function searchCategories(Request $requ ...

An optional field has been identified as ng-invalid

In my set-up, I have created a form group using reactive forms. this.transactionForm = fb.group ({ 'location': [null, Validators.required], 'shopper': [null], 'giftMessage': [null], 'retailPrice& ...

collapse each <b-collapse> when a button is clicked (initially shown)

I am facing an issue with a series of connected b-buttons and b-collapse, all initially set to be visible (open). My goal is to hide them all when a toggle from my parent.vue component is activated - so upon clicking a button in the parent component, I wa ...

Is it possible to add checkboxes for all items and only for the current items in VueJS using Bootstrap-V

I'm currently utilizing the bootstrap-vue b-table along with the b-pagination component, loading approximately 50 items per page. Each row contains a b-form-checkbox. I've encountered challenges in achieving the following: 1) Connecting the chec ...

Update your code to use the fetch API instead of axios

Looking to switch my axios post call to a fetch call: export async function createFriend ({ let myData = new FormData() myData.append('name', name) myData.append('age', age) const response = await axios.post('/myApi/friends ...

Is there a way for the parent component to wait until the child has returned data to it? (Implemented in Vue 2)

Explaining the Situation - In my project, I have a complex form divided into components. In this discussion, I will focus on a specific parent-child component relationship for simplicity. I am performing validation on each child component and sending th ...

The attribute 'getValue' is not a valid property for the data type 'Subject<boolean>'

Currently, I am working with Angular2 and have a BehaviorSubject. isOpen$: Subject<boolean> = new BehaviorSubject<boolean>(true); When I try to retrieve the latest value using: isOpen$.getValue() It functions correctly, however, there is a ...

Exploring the archives of PubNub within Angular5

I've been working on integrating PubNub history into my web app, but I'm currently only able to view it in the console. Here's what I have so far: pubnub.history( { channel: 'jChannel', reverse: false, ...

Discover the power of sharing a service instance in Angular 2 RC5

In the past, I shared a service instance by declaring it as a viewInjectors within my @Component like so: @Component({ selector: 'my-sel', viewInjectors: [SharedService], templateUrl: 'template.html', pipes: [MyPipe] }) ...

Retrieving the final selection made in vuetify v-select

Can someone please explain how to retrieve the last selected or removed value in a vuetify v-select when using the multiple property? For example, let's say we have a v-select with items [ 'Choice A', 'Choice B', 'Choice C&ap ...

Steering clear of Unfulfilled Promises in TypeScript. The Discrepancy between Void and .catch:

When it comes to handling promises in TypeScript, I'm used to the then/catch style like this: .findById(id) .then((result: something | undefined) => result ?? dosomething(result)) .catch((error: any) => console.log(error)) However, I have also ...

Displaying a 404 error page in a Vue.js and Vue Router single-page application when a resource is not

Implementing Vue and Vue Router in a single page application (SPA) has presented me with a challenge. In one of my view components, I query a repository for a specific resource. If the resource cannot be found, I'd like to display a 404 error page wit ...

Leveraging MathJax within a Typescript/Angular2 component

Struggling with calling the MathJax.Hub functions in my angular2 component. Spent hours trying to figure it out last night. Need to use the MathJax API to re-render dynamically bound InnerHTML string. However, unable to access the MathJax global variable ...

Having trouble getting SQLite to function properly in Ionic 2

Encountering issues with implementing SQLite plugin in my Angular 2/Ionic 2 project. Following the Ionic 2 documentation for instantiating SQLite is not yielding expected results. Received an error message from Sublime: Supplied parameters do not matc ...