In Vue, we can hide or display data through v-if, v-show, computed properties or methods. Below, let’s take a closer look at these methods.
<template> <div> <div v-if="isShow">这是要显示的数据</div> <div v-else>这是要隐藏的数据</div> </div> </template> <script> export default { data() { return { isShow: false } } } </script>
In this example, we use a Boolean type data isShow to control whether to display or hide data. When the value of isShow is true, the data to be displayed will be displayed; otherwise, it will be hidden.
<template> <div> <div v-show="isShow">这是要显示的数据</div> </div> </template> <script> export default { data() { return { isShow: false } } } </script>
Unlike v-if/v-else, v-show displays and hides data by controlling the CSS display property. When the value of isShow is true, the data to be displayed will be displayed, and the display attribute is the value set for the element, such as block by default; otherwise, it will be hidden, and the display attribute is none.
v-if/v-else and v-show have different usage scenarios. v-if/v-else is suitable for use when frequent switching is required, because it will only work when the conditions are met. Render the corresponding content, then destroy and re-render when the conditions are not met; v-show is suitable for use when the initial rendering needs to control the display or hiding of data based on conditions, because it simply controls the CSS display property.
<template> <div> <div>{{ message }}</div> </div> </template> <script> export default { data() { return { isShow: false, content: '这是要显示的数据' } }, computed: { message() { if(this.isShow) { return this.content } else { return '' } } } } </script>
computed properties can dynamically calculate some values in the template and return the calculation results to the template for rendering. In the above example, we use the message method in the computed computed property to dynamically change the data to be displayed based on changes in the isShow value.
<template> <div> <div>{{ getMessage() }}</div> </div> </template> <script> export default { data() { return { isShow: false, content: '这是要显示的数据' } }, methods: { getMessage() { if(this.isShow) { return this.content } else { return '' } } } } </script>
methods method can dynamically call a method in the template and return the return value of the method to the template for rendering. In the above example, we used the getMessage method in the methods method to dynamically change the data to be displayed based on changes in the isShow value.
No matter which method is used, the key is to choose the appropriate method to hide or display data according to the specific scenario.
The above is the detailed content of How to display hidden data in vue. For more information, please follow other related articles on the PHP Chinese website!