vue.js 如何使用v-show切换模板

oyt4ldly  于 2023-06-24  发布在  Vue.js
关注(0)|答案(2)|浏览(117)

我正试图切换使用v-showv-if模板的存在,如下面发布的代码所示。
我面临的问题是,尽管v-show不是一个懒惰的条件,当我设置showTemplate为false或true时,msg的内容总是显示
请让我知道如何正确使用v-showv-if

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>

应用

template>
  <img alt="Vue logo" src="./assets/logo.png">
  <HelloWorld msg="Welcome to Your Vue.js App"/>
</template>

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

<script setup>

</script>
jecbmhm3

jecbmhm31#

你必须这样使用:

<template>
  // v-show or v-if it doesn't matter
  <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>

导致v-if或v-show不适用于template属性。

xdnvmnnf

xdnvmnnf2#

试试下面的代码段:

const { ref } = Vue
const app = Vue.createApp({
  setup() {
    let showTemplate = ref(false)
    return { showTemplate }
  },
})
app.component('child', {
  template: `<div class="hello">{{ msg }}</div>`,
  props: {
    msg: String
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <img alt="Vue logo" src="./assets/logo.png">
  <button @click="showTemplate = !showTemplate">toggle</button>
  <child v-if="showTemplate" msg="hello component"></child>
</div>

相关问题