SoFunction
Updated on 2025-04-05

Causes and solutions for v-if failure in vue

Generally, v-if failure is related to binding variables. There are generally two types of things I know

1. The bound variable is String type or other type

It means that the returned variable type does not match the required boolean type.

<template>
     <div>
       <div  ref="container" v-if='type'></div>
    </div>
</template>
<script setup lang="ts">
  const type=ref('false')
</script>

Like this, the value of the type we get is "false" instead of false, and the type is different between the two. If you are not sure about the variable type, use typeof to print.

2. Two similar components, v-if cannot be judged

For two very similar components, whether custom or self-defined, if you just use v-if, it may cause failure

<template>
     <div>
       <el-button  v-if='type'></el-button>
       <el-button  v-if='!type'></el-button>
    </div>
</template>
<script setup lang="ts">
  const type=ref(false)
</script>

Like this, but we can distinguish it by adding key values.

<template>
     <div>
       <el-button  v-if='type' key=1></el-button>
       <el-button  v-if='!type' key=2></el-button>
    </div>
</template>
<script setup lang="ts">
  const type=ref(false)
</script>

This will take effect.

This is the article about the causes and solutions for v-if failure in vue. This is the end. For more related vue v-if failure content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!