简体   繁体   English

如何在 Vue.js 中有条件地渲染元素?

[英]How to render an element conditionally in Vue.js?

I'm new to Vue.js, I just read the documentation on conditional rendering here ( https://v2.vuejs.org/v2/guide/conditional.html ) but somehow can't get it to work...我是 Vue.js 的新手,我只是在这里阅读了有关条件渲染的文档( https://v2.vuejs.org/v2/guide/conditional.html ),但不知何故无法让它工作......

My code:我的代码:

<button onclick="showTemplate()">Teste</button>


<template v-if="app">

    <div id="app">
      {{ message }}
    </div>

</template>

function showTemplate(){
    var app = new Vue({
      el: '#app',
      data: {
        message: 'Hello Vue!'
      }
    })
}

I want the template tag to render only after app has been instantiated.我希望模板标签仅在应用程序实例化后才呈现。 I have also tried variations of this code without success.我也尝试过这段代码的变体,但没有成功。 Can someone help out?有人可以帮忙吗?

Use v-cloak .使用v-cloak The intended use of v-cloak is to hide the Vue until it is instantiated. v-cloak的预期用途是隐藏 Vue,直到它被实例化。

 function showTemplate() { var app = new Vue({ el: '#app', data: { message: 'Hello Vue!' } }) }
 [v-cloak] { display: none; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script> <button onclick="showTemplate()">Teste</button> <div id="app" v-cloak> {{ message }} </div>

Here is how you might hide your "loading" screen when data is retrieved.这是在检索数据时隐藏“加载”屏幕的方法。 In this case, the button will serve as our loading screen.在这种情况下,按钮将作为我们的加载屏幕。

 var app = new Vue({ el: '#app', data: { message: 'Hello Vue!', loaded: false }, methods: { getData() { setTimeout(() => this.loaded = true, 2000) } } })
 [v-cloak] { display: none; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script> <div id="app" v-cloak> <button v-if="!loaded" @click="getData">Get Data</button> <div v-if="loaded"> {{ message }} </div> </div>

Try this and remove the button.试试这个并删除按钮。 You don't need to call the instance within the function.您不需要在函数中调用实例。

// put it on your index.html
<div id="app">
  {{ message }}
</div>

// put it on your script make sure that you have already a CDN of vuejs.
var app = new Vue({
   el: '#app',
   data: {
      message: 'Hello Vue!'
   }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM