What could be causing my Vue code to behave differently than anticipated?

There are a pair of components within the div. When both components are rendered together, clicking the button switches properly. However, when only one component is rendered, the switch behaves abnormally.

Below is the code snippet:

Base.vue

<template>
  <div :id="id">{{msg}}</div>
</template>

<script lang='ts'>
import { Component, Prop } from "vue-property-decorator";
import Vue from "vue";

@Component
export default class Base extends Vue {
  id!: string;
  msg = "this is Base";
}
</script>

child.vue (no template)

<script lang='ts'>
import Base from "@/components/Base.vue";
import { Prop, Component } from "vue-property-decorator";
@Component
export default class extends Base {
  @Prop({ default: "helloWorld" })
  childId!: string;
  constructor() {
    super();
    this.id = this.childId;
    this.msg = "this is Child " + this.childId;
  }
}
</script>

App.vue (displays these components)

<template>
  <div id="app">
    <Child v-show="!show" childId="child1" style="color:#f00;"/>
    <button @click="click">change</button>
    <Child v-show="show" childId="child2" style="color:#f0f;"/>
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import Child from "@/components/Child.vue";
import Component from "vue-class-component";

@Component({
  components:{
    Child,
  }
})
export default class App extends Vue {
  show= false;
  click() {
    this.show = !this.show;
  }
}
</script>

After clicking the button, the expected result is displayed.

If all instances of v-show in the App.vue file above are changed to v-if, the result becomes confusing upon clicking the button.

Subsequent to clicking the button, the unexpected result is shown instead of child2. This raises the question as to why this occurs.

Answer №1

When you click for the first time, you are actually creating the show-property that was missing because the data() method was not set up correctly.

I won't delve into the specific reasons why this happened, but it seems like there may have been some unexpected boolean conversions and the property might not be reactive since it wasn't included in the data object. In any case, simply create it as shown below and everything should function as intended:

export default class App extends Vue {
  data(){ 
     return {
       show: false
     }
  },
  click() {
    this.show = !this.show;
  }
}

Answer №2

Thank you so much!

After experimenting with different keys for each Child component, I successfully resolved this issue.

<Child v-if="!show" childId="child1" key="goodbye1" style="color:#00f;" />
<Child v-if="show" childId="child2" key="goodbye2" style="color:#0ff;" />

In my opinion, Vue's diff algorithm is the reason behind considering these two components as identical.

Answer №3

When utilizing the v-if directive, it will utilize the same instance of the Child component. The value of this.msg will only be set once in the constructor. The value of msg will not update when the childId props change, hence the need for the Watch property. It is important to use Watch to ensure that when the childId changes, the msg is updated accordingly.

Child.vue

<script lang='ts'>
import Base from "@/components/Base.vue";
import { Prop, Component, Watch } from "vue-property-decorator";
@Component
export default class extends Base {
  @Prop({ default: "helloWorld" })
  childId!: string;
  @Watch('childId')
  onChildIdChanged(val: any) {this.msg = "this is Child " + val}
  constructor() {
    super();
    this.id = this.childId;
    this.msg = "this is Child " + this.childId;
  }
}
</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

What are the consequences of altering meta tags once the DOM has fully loaded?

While delving into the A-Frame source code, I noticed that the library uses JavaScript to set various meta tags. It seems safe in the context of A-Frame as Mozilla recommends importing their library as a blocking, synchronously loaded script in the <he ...

The variable $ has not been defined in Jquery framework

<html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script type="text/javascript" src="deployJava.js"></script> <script type="text/javascr ...

The functionality of a jQuery click event may cease to work once a loader has been incorporated into a

Since implementing a loading feature in my Vue template, I have encountered issues with jQuery not functioning properly: var element = document.getElementById('vue-project') if (element !== null) { var getData = await axios.get('./dat ...

Images in the JavaScript menu are not remaining fixed in place

Can someone help me with my website? I'm having trouble with the menu for different pages, it should stay gray for the active page. It was working fine before I switched to Wordpress, but now I'm not sure what the issue is. Could someone take a ...

Dynamically remove values from other fields in a React Formik form based on checkbox conditions

Currently, I am utilizing react-formik for my form implementation. I have encountered an issue with checkbox-based conditions where the checked status of a checkbox determines whether two hidden fields are displayed or hidden. If the user checks the checkb ...

Updating Mysql through REST API/JWT using PUT method is not possible

I have been attempting to send an update request using Jwt (Tokens) and Node.Js with a backend in mysql. While Postman confirms that the record has been successfully updated, I am unable to locate where the actual update occurred. No changes seem to be ref ...

Secure your data with public key encryption and decryption using the Crypto Module in NodeJS

I have a challenge with encrypting/decrypting data using a public key that is stored in a file. The code snippet below illustrates my approach: encryptWithKey (toEncrypt, publicKeyPath) { var publicKey = fs.readFileSync(publicKeyPath, "utf8"); ...

Exploring user inputs and displaying variables using JavaScript and HTML 4.01

I was testing some code and I'm facing an issue that I can't figure out: <HTML> <head> <title> Page 1 </title> <script> function myFunction() { var x=document.getElementById("myEmail") document.write(x) } </scr ...

Is it possible to create an instance in TypeScript without using class decorators?

As per the definition on Wikipedia, the decorator pattern enables you to enhance an object of a class with additional functionalities, such as: let ball = new BouncyBall(new Ball()) The Ball object is adorned with extra features from the BouncyBall class ...

ALSO, various criteria

function findLogicalAND(){ let result; let index; for (index = 0; index < arguments.length; index++){ result = arguments[index] && arguments[index+1]; } return result; } console.log(findLogicalAND(true, true, false, false)); I want to r ...

The module for the class could not be identified during the ng build process when using the --

Encountering an error when running: ng build --prod However, ng build works without any issues. Despite searching for solutions on Stack Overflow, none of them resolved the problem. Error: ng build --prod Cannot determine the module for class X! ...

Is there an error when iterating through each table row and extracting the values in the rows?

Here is a basic table that I am attempting to iterate through in order to retrieve the value of each cell in every row where there are <td>s present. However, I encounter an error indicating that find does not exist despite having added jQuery. Any ...

Resizing a scrollable list using React Refs and UseLayoutEffect

Essentially, my issue stems from having a scrollable list with a set maximum height of '100vh'. I also have a detail card beside the list that contains accordion components. When one of these accordions is expanded, it increases the height of the ...

Issue with displaying PDF files on Google Chrome due to a software glitch

Recently, I encountered a puzzling issue on Google Chrome. I am not sure if the error lies with Google or within my code. When I set the div as display: none; and then show it again, the PDF view only shows a grey background. However, if I zoom in or out, ...

Can a Jquery *compiler* be developed?

Upon encountering this informative question, the idea of creating a jQuery compiler crossed my mind. The concept was to design a tool that could translate jQuery code into raw JavaScript code for execution. In my imagination, the process of executing a bl ...

Change the text inside a container without losing any associated event listeners using JavaScript or jQuery

Here is the HTML code: <div id="div001"> This is ${Row.1}. <p>${Row.2} explain something else.</p> <p>${Row.3} welcome you. <span>${Hello.World}, this is a new world.</span></p> </div> My objective is ...

Is there a way to update JSON data through a post request without it getting added to the existing data?

Hello, I am currently delving into Angular2 and encountering a problem concerning RestAPI. When I send a post request to the server with a JSON file, I intend to update the existing data in the JSON file; however, what actually happens is that the new data ...

Most efficient method for comparing two JSON arrays and rearranging their positions

I am faced with a challenge involving two Javascript JSON arrays. The arrays in question are named this.BicyclePartsOLD and this.BicyclePartsNEW. Both arrays contain an attribute named "ListOrder". The OLD array is currently ordered from ListOrder 1 to n ...

Error: The variable 'error' could not be located

Below is the code that I am using: $(document).ready(function(){ var callPage = function(){ $.post('/pageToCall.php'); }; setInterval('callPage()', 60000); }); However, I encountered an error stating ReferenceErro ...

Bootstrap typehead not activating jQuery AJAX request

I am attempting to create a Twitter Bootstrap typehead using Ajax, but nothing seems to be happening. There are no errors and no output being generated. Here is the jQuery Ajax code I have implemented: function CallData() { $('input.typeahea ...