Building/Deleting the Vue Component using text search

In my App.vue file, I have the following setup:

<template>
    <div id="app">
        <input type="text" v-model="term">
        <hello-world text="Button 1" v-if="term === ''"></hello-world>
        <hello-world v-else text="Button 2"></hello-world>
    </div>
</template>

<script>
import HelloWorld from '@/components/HelloWorld'

export default {
    name: 'app',
    data() {
        return {
            term: ''
        }
    },
    components: {
        HelloWorld
    }
}
</script>

And here is the content of HelloWorld.vue:

<template>
    <div>
        <button>{{ text }}</button>
    </div>
</template>

<script>
export default {
    props: {
        text: String
    },
    created() {
        console.log('Created')
    },
    destroyed() {
        console.log('Destroyed')
    }
}
</script>

However, when I input text, the expected behavior does not occur. The component is neither destroyed nor created as expected by the v-if condition. Can someone provide assistance with this issue? Thank you.

Answer №1

Vue operates using a virtual dom approach, which means it compares the virtual tree instead of identifying changes in structure (oldNode.type === newNode.type). This allows Vue to update the same component without destroying the old node and creating a new one.

To manipulate Vue into detecting virtual tree changes, try to avoid using siblings with the same tag name controlled by the v-if directive.

For more information, refer to:

https://medium.com/@deathmood/how-to-write-your-own-virtual-dom-ee74acc13060

Vue.component('hello-world', {
  props: {
    text: String
  },
  created() {
    console.log('Created')
  },
  destroyed() {
    console.log('Destroyed')
  },
  template: "<button>{{ text }}</button>"
});

var app = new Vue({
  el: "#app",
  data() {
    return {
      term: ''
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input type="text" v-model="term">
  <span><hello-world v-if="!term" text="Button 1"></hello-world></span>
  <span><hello-world v-if="term" text="Button 2"></hello-world></span>
</div>

Answer №2

Uncertain of your goal, however evaluating the code logs generated by both elements https://codesandbox.io/s/8l0j43zy89 Given that you are conditionally displaying the identical component, destruction seems unlikely.

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

Customizing the Slider Range with HTML DOM Style's BackgroundImage Attribute

I have a slider range that I'd like to modify using JavaScript. Specifically, I want to change its background-image property. To achieve this, I attempted the following script: document.getElementById("range").style.backgroundImage = "linear-gradient ...

What is a way to execute a series of requests using rxjs similar to forkJoin and combineLatest, without needing to wait for all requests to finish before viewing the results?

Consider you have a list of web addresses: urls: string[] You create a set of requests (in this instance, utilizing Angular's HTTPClient.get which gives back an Observable) const requests = urls.map((url, index) => this.http.get<Film>(url) ...

Display a dialog box in jQuery UI 1.7 autocomplete when an item is selected

After implementing an autocomplete widget, I noticed that a dialog appears when an item is selected. However, I am struggling to get a specific field in the dialog to receive focus upon opening. Here is what I have attempted so far: //HTML <form actio ...

After clicking the submit button, make sure to automatically fill in all empty input fields

I am currently working on a form that includes various input types such as text fields, radio buttons, select dropdowns, and text areas. The form is displayed in a table format with an option to add additional rows. One issue I have encountered is that us ...

Is it acceptable to use the return value of false in order to resolve the ESLint consistent-return error when working with asynchronous functions

When working with ExpressJS, I encountered a situation where I needed to execute and adhere to ESLint rules in my code. One particular rule that caused an issue is "consistent-return", which flagged the following code snippet: function getUsers( req, res, ...

Getting Creative with Jquery Custombox: Embracing the 404

Encountering a problem with jquery custombox version 1.13 <script src="scripts/jquery.custombox.js"></script> <script> $(function () { $('#show').on('click', function ( e ) { $.fn.custombox( this, { ...

Tips for accessing data in Vue.js pug templates:

Essentially, my goal is to create a permalink from an event name. I am able to retrieve the value from the event name using v-model successfully, but I'm having trouble figuring out how to input the converted permalink into another input box in pug. ...

The method to permit a single special character to appear multiple times in a regular expression

I am currently working on developing a REGEX pattern that specifically allows alphanumeric characters along with one special character that can be repeated multiple times. The permitted special characters include ()-_,.$. For instance: abc_def is conside ...

Alert for JavaScript Increment (++) Operation

While reviewing my code using jslint, I noticed a warning regarding the increment operator: var x = 1; x++; Warning: Unexpected expression '++' in statement position. According to the documentation: "They are second only to faulty archi ...

What could be causing this highchart plot to fail to display in both IE and Chrome?

Check out the plot in this jsfiddle: http://jsfiddle.net/essennsee/y5HCm/ The plot looks good in Firefox, but only shows the legend in IE and Chrome. If I remove the following code snippet it works fine. Is there a different way to format the labels?: ...

Rails 4 application encountering issues with rendering views when making a $.ajax request

I am a beginner in Rails and I am in the process of sending model data to a controller method from JavaScript for rendering a list of results... function submitResults() { resultURL = "/result"; resultData = JSON.stringify(results); $.ajax({ typ ...

Saving numerical data from Firebase using Vue.js

I am currently using Firebase in combination with Vue.js. When saving data to the database, I execute the following command: saveEvent(){ db.collection('events').add({ title: this.title, content: this.content, start: this.start, ...

Idiosyncratic TypeScript behavior: Extending a class with comparable namespace structure

Lately, I've been working on creating a type library for a JavaScript written library. As I was defining all the namespaces, classes, and interfaces, I encountered an error TS2417 with some of the classes. I double-checked for any issues with method o ...

Tips for transforming list items into an array of strings

let typeList="[Product,Task,Invoice,Media,Store]"; I need to transform the string above into an array like this:- let typeList=["Product","Task","Invoice","Media","Store"]; Any help with this is greatly appreciated. ...

Tips for avoiding a button reverting to its original state upon page refresh

I have a button with the ID #first that, when clicked, is replaced by another button with the ID #second. However, if I refresh the page after clicking on the second button, it goes back to displaying the first button. Is there a way to make sure that th ...

Troubleshooting EJS Relative Path Problem when Using "include" in an HTML Document

I'm encountering an issue with my "index.ejs" file... The current content of the ejs file: <!DOCTYPE html> <html lang="en" dir="ltr"> <!-- THIS SECTION IS FOR <head> TAG THAT WILL BE STORED INSIDE "so_ ...

The stubborn Node and Passport are refusing to update the password using user.setPassword

Currently, I am working on setting up my program to update a user's password only when the old one is confirmed as correct. Most of the code functions as expected except for one specific line: router.put("/:id/edit_password", isLoggedIn, isAdministra ...

Encountering installation issues with npm for bcrypt installation due to a

While working on an Express JS project, I encountered issues trying to install the bcrypt module for data authentication. Despite multiple attempts, I kept receiving the same errors. [email protected] install /media/iron/1d6c195f-2350-423c-a3f0-050 ...

Encountering NaN while trying to retrieve the duration in JavaScript

I'm having an issue retrieving the duration of an mp4 video file when the HTML document loads. Here's my code: (function ($, root, undefined) { $(function () { 'use strict'; $(document).ready(function() { ...

Issue with implementing bootbox and jQuery.validator for AJAX login form collaboration

Here's a fiddle link that showcases the issue I'm facing. The problem arises when I try to Sign In on an empty modal form. The validator should highlight any fields in error and proceed to submit the form once the validation is successful. I&ap ...