Home  >  Q&A  >  body text

Learn to use v-show to switch templates

I'm trying to use v-show or v-if to toggle the display of the template as shown in the code below.

The problem I'm facing is that although v-show is not a lazy condition, when I set showTemplate to false or true, msg The content is always displayed.

Please tell me how to use v-show and v-if correctly.

helloWorld

<template v-show="showTemplate">
  <div class="hello">
  {{msg}}
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  }
}
</script>

<script setup>
    import { ref } from 'vue'
    let showTemplate = ref(true)
    showTemplate.value=false
</script>

app:

template>
  <img alt="Vue logo" src="./assets/logo.png">
  <HelloWorld msg="欢迎使用Vue.js应用程序"/>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
  name: 'App',
  components: {
    HelloWorld
  }
}
</script>

<script setup>


</script>
P粉680087550P粉680087550402 days ago493

reply all(1)I'll reply

  • P粉344355715

    P粉3443557152023-09-13 13:14:18

    You must use it like this:

    <template>
      // v-show或v-if都可以
      <div v-show="showTemplate" class="hello">
      {{msg}}
      </div>
    </template>
    
    <script>
    export default {
      name: 'HelloWorld',
      props: {
        msg: String
      }
    }
    </script>
    
    <script setup>
        import { ref } from 'vue'
        let showTemplate = ref(true)
        showTemplate.value=false
    </script>

    Because v-if or v-show cannot be used with the template attribute.

    reply
    0
  • Cancelreply