VueJS does not show a component if it is contained within a v-if or v-show directive

My goal is to show a component when the 'Add Patient' button is clicked using a v-if directive:

// within <template></template>
<button type="button" class="btn btn-info" @click="showPatientForm">Add a patient</button>
...
<div class="d-flex flex-column w-75 contentOrder">
    <div class="" v-if="showArticle" ref="patientOk"> <!-- display articles if patient exists -->
        <ArticleCmp/>
    </div>
    <div class="hidden" ref="patientNotOk" v-else> <!-- Show form to add a new patient -->
        <PatientForm :addPatient="addPatient"/>
    </div>
</div>

// within <script></script>, export default(){ methods:... }

showPatientForm(){
        try{
                const createPatient = this.$refs.patientNotOk // Locate the form <div>
                createPatient.classList.remove('hidden') // Remove the hidden class
            }
        catch(err){
                console.error(err)
        }
},

I understand that this approach may not be ideal, as changing the v-else to v-if causes issues when switching between an existing patient and creating a new one.

The challenge lies in ensuring that when clicking on an existing patient and then trying to create a new one, this.$refs.PatientNotOk returns null. This is because VueJS (Vite 3) does not initially render the v-else since it is false. How can I force the rendering of the v-else?

Here's the error log :


TypeError: createPatient is null
    showPatientForm CreateOrderView.vue:127
    2 CreateOrderView.vue:33
    callWithErrorHandling runtime-core.esm-bundler.js:173
    callWithAsyncErrorHandling runtime-core.esm-bundler.js:182
    invoker runtime-dom.esm-bundler.js:345
CreateOrderView.vue:131:25
    showPatientForm CreateOrderView.vue:131
    2 CreateOrderView.vue:33
    callWithErrorHandling runtime-core.esm-bundler.js:173
    callWithAsyncErrorHandling runtime-core.esm-bundler.js:182
    invoker runtime-dom.esm-bundler.js:345

(line 131 corresponds to the console.error within the catch block, line 127 is where createPatient.classList.remove is called, and line 33 refers to the 'Add a patient' button in the template)

Answer №1

When using the ref function in Vue, ensure that you assign variables with the same names.

const studentNotOk = ref();
const studentOk = ref();

Below is a functional script setup :

<script setup>
import { ref } from "vue";
const studentNotOk = ref();
const studentOk = ref();
const showStudentForm = () => {
  try {
    const createStudent = studentNotOk.value; // Locate the form element
    createStudent.classList.remove("hidden"); // Remove the hidden class
  } catch (err) {
    console.error(err);
  }
};
</script>

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

The q library ensures that a value is delivered to the done method

I am seeking to understand the purpose and usage of the `done` method in the Q library promises. If `done` is able to receive a value or function through `resolve` or `reject`, could someone clarify how the `done` method is invoked and how arguments can ...

Vue, anticipate the Watch

My application has a similar structure when it comes to architecture. computed(){ currentValue = this.$store.currentValue; } watch() { currentValue() = async function () { //perform asynchronous action } }, methods: { updateValue( ...

Obtaining an array through an AJAX request in JavaScript

I'm struggling with my ajax call setup: request = new XMLHttpRequest(); request.open("GET","/showChamps?textInput=" + searchChamp.value,true); request.send(null); request.onreadystatechange = function () { if (request.status == 200 && reques ...

NPM encountered difficulties in resolving the dependency tree

I seem to be encountering a persistent issue that I cannot resolve on my own. My attempt to update webpack and webpack-cli in a project has been met with repeated errors of this nature: npm install webpack@latest --save-dev npm ERR! code ERESOLVE npm E ...

When using a Kendo Grid with a Checkbox as a column, the focus automatically shifts to the first

Whenever I select a checkbox in my Kendo grid, the focus automatically shifts to the first cell of the first row. How can I prevent this from happening? Here is the code I am currently using when a checkbox is checked: $('#approvaltranslistview' ...

What is causing this to function properly on Firefox but not on Chrome or IE?

After clicking the process_2banner button on my html page, a piece of code is executed. Surprisingly, this code performs as expected in Firefox, but not in Chrome or Internet Explorer. In those browsers, although the ajax code is triggered, the div spinner ...

Creating a response in Node JS

I'm struggling with crafting a response to the server. Currently, I have a login form that sends data to the server. On the backend, I verify if this data matches the information in a .json file and aim to send a response upon successful validation. ...

Learn how to implement datatables in your web application by combining Vue.js with Laravel

I'm currently populating a table and I want to implement pagination, searching, and filter criteria. However, as a newcomer to Vue, I'm unsure how to incorporate these features into my code. Here is the content of my Vue file: <template> ...

Can you explain how the interactive notification on stackoverflow is generated when you are responding to a question and someone posts a new answer?

Have you ever been in a situation where you're writing an answer to a question, but then someone else posts their response and a popup appears notifying you of the new answer? I'm curious about how that whole process works. It seems like the answ ...

Utilize a generic data type for a property that can accept values of type 'number', 'string', or 'undefined'

This query involves React code but pertains to typescript rather than react. To simplify, I have a component called MyList which accepts a single generic type argument passed to the props type. The generic type represents an object that will be used to c ...

Setting a cookie within an Angular interceptor

My angular interceptor function includes a request object. intercept(req: HttpRequest<any>, next: HttpHandler) { return next.handle(req); } I am looking to set my token in the request cookie under the name my-token. How can I achieve this? I ...

What are some more efficient methods for implementing page location detection with Angular directives?

My website currently features a navigation bar with 4 anchor links that direct users to different sections of the page. As you scroll down the page, the corresponding link on the nav bar lights up to signify your position on the site. Experience it yourse ...

How can VueJS manipulate state with Mutation?

I have set up a Vuex Store that returns data on headers and desserts. The desserts object includes a property called display, which is initially set to false. In my project, I am using a component called Row within another component named Table. The Row co ...

Adjusting the size of a dynamically generated rectangle using DrawingManager

I am currently working on a web application using Azure Maps along with the DrawingManager library. My goal is to allow users to save a drawn rectangle and potentially edit it by resizing later on. The strange thing is that while resizing rectangles works ...

Creating a template / component in Vue.js 2 with two identical files

Currently using Vue.js 2.0, I find myself duplicating the exact same code in two different files, with only the ID_SPECIFIC_TO_THIS_BLOCK being different. As a Vue beginner, I am curious to know if there is a way to create a reusable template that can be u ...

The directive code takes precedence over the controller code and is executed first

A custom directive has been implemented and is utilized as shown below: <div car-form car="car" on-submit="createCar(car)"></div> This directive is used on both the new and edit pages, each with its own controller. The EditCarController retri ...

Vue - Continue to fetch all items asynchronously within a for loop

I am facing a challenge where I have an array of data that needs to be fetched using a for loop. However, I want to fetch this data asynchronously to make multiple calls at the same time. Additionally, once all the data has been fetched, I need to perform ...

Incorporating video.js into an Angular website application

I've encountered a strange issue while attempting to integrate video.js into my angular app. <video id="example_video_1" class="video-js vjs-default-skin" controls preload="none" width="300" height="264" poster="http://video-js.zenco ...

Having difficulty communicating with the smart contract using JavaScript in order to retrieve the user's address and the balance of the smart contract

Hi there, I am a newcomer to the world of blockchain technology. Recently, I created a smart contract designed to display both the contract balance and user data, including the address and balance of the user. The smart contract allows users to deposit fun ...

Is it advisable to incorporate await within Promise.all?

Currently, I am developing express middleware to conduct two asynchronous calls to the database in order to verify whether a username or email is already being used. The functions return promises without a catch block as I aim to keep the database logic se ...