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.