Analysis of conditional rendering function examples in Vue documents
Vue is a very popular JavaScript framework. It provides some tools and functions that are convenient for developers, allowing developers to build complex web applications more conveniently. Among them, the conditional rendering function is a very useful function in Vue, which can help developers dynamically control and render elements on the page. In this article, we will analyze and demonstrate the conditional rendering function in the Vue document.
1. Introduction to Vue’s conditional rendering function
You can use the v-if and v-show instructions in Vue to implement conditional rendering. These instructions allow us to control whether certain elements need to be rendered on the page based on conditions.
The v-if directive determines whether an element needs to be rendered based on the value of the expression. If the value of the expression is true, the element will be rendered; otherwise, the element will not be rendered. For example:
<div v-if="shown"> 这是一个需要被渲染出来的div元素 </div>
In the above example, the div element will be rendered on the page only when the value of the shown attribute of the Vue instance is true.
The v-show directive can also implement conditional rendering of elements, but its implementation is a bit different from v-if. The v-show instruction dynamically changes the display attribute of the element based on the value of the expression. If the value of the expression is true, the display attribute of the element is set to block, so that the element is displayed on the page; otherwise, the element's display attribute is set to block. Setting the display attribute to none causes the element to be hidden on the page. For example:
<div v-show="shown"> 这是一个需要被渲染出来的div元素 </div>
In the above example, as long as the value of the shown attribute of the Vue instance is true, the div element will be displayed, otherwise it will be hidden.
2. Differences between v-if and v-show
Although both v-if and v-show can achieve conditional rendering of elements, they are different in their implementation methods. Mainly manifested in the following aspects:
- Rendering overhead
The v-if instruction re-judges the value of the conditional expression every time it is rendered, and based on the The value of an expression to add or remove elements. Therefore, when the value of the conditional expression is complex or there are many elements, the rendering overhead of v-if will be relatively large.
The v-show instruction only hides or displays elements by dynamically changing the display attribute of the element. There is no need to recreate or remove the element, so the rendering overhead is relatively small. However, during the initial rendering of the element, the v-show instruction needs to first determine the value of the conditional expression and set the display attribute of the element based on this value, so the rendering speed may be slower than v-if.
- Initialize rendering overhead
The v-if instruction will not render when the conditional expression is initially false. Rendering will only start when the value of the conditional expression becomes true. Therefore, the initial rendering overhead of v-if will be smaller than that of v-show.
The v-show instruction will dynamically set the display attribute of the element based on the value of the conditional expression during initial rendering, thereby determining whether the element is displayed. Therefore, the initial rendering overhead of v-show will be larger than that of v-if.
- Rendering performance
The v-if instruction will re-judge and re-create or remove the corresponding element when the value of the conditional expression changes. When only a small number of elements need to be rendered dynamically, the performance of v-if will be slightly better than v-show.
The v-show command only controls the display and hiding of elements by dynamically changing the display attribute of the element. There is no need to recreate or remove the element. Therefore, when it is necessary to frequently switch the display and hiding of elements, the performance of v-show will be better than v-if.
3. Selection of v-if and v-show usage scenarios
Based on the above differences, we can choose v-if and v-show according to actual needs.
When you need to frequently switch the display and hiding of elements, you can choose to use the v-show command. For example: used to show and hide certain operation panels or dialog boxes, switch menus, etc.
When you need to determine whether certain elements need to be rendered based on complex logic, or when you need to dynamically create or remove elements, you can use the v-if directive. For example: rendering certain elements in the page according to the user's login status, rendering certain operation buttons in the page according to the user's permissions, etc.
4. Example Analysis
Let’s demonstrate the use of v-if and v-show based on an example.
Suppose we need to display a list of products on the page. The list contains information such as product name, price, inventory, and purchase button. At the same time, the list also needs to provide a filtering function so that users can view different product information based on different conditions. The specific implementation is as follows:
- Define product list data
First we need to define an array containing product information. Here we temporarily assume that the array already contains 10 products. information. The format of the array is as follows:
goodsList: [ { name: "商品A", price: 100, stock: 50 }, { name: "商品B", price: 200, stock: 80 }, ... ]
- Define filter conditions and filter result data
In order to implement the filter function, we need to define a form that contains the Filter condition input box. Through these input boxes, users can enter different filtering conditions to view different product information.
At the same time, we also need to define a variable to store the filtered results, so as to filter out products that do not meet the filtering conditions. The definitions of filter conditions and filter results are as follows:
filterForm: { name: "", minPrice: "", maxPrice: "" }, filteredGoodsList: []
- 实现筛选逻辑
为了实现筛选功能,我们需要在Vue实例中定义一个方法,该方法会在每次需要筛选时被调用。该方法会根据用户输入的筛选条件,从商品列表中筛选出符合条件的商品,并将结果存储到filteredGoodsList中。
具体实现代码如下:
methods: { filterGoodsList() { let filterName = this.filterForm.name.toLowerCase() let filterMinPrice = this.filterForm.minPrice ? parseInt(this.filterForm.minPrice) : Number.MIN_SAFE_INTEGER let filterMaxPrice = this.filterForm.maxPrice ? parseInt(this.filterForm.maxPrice) : Number.MAX_SAFE_INTEGER this.filteredGoodsList = this.goodsList.filter((item) => { let itemName = item.name.toLowerCase() return itemName.indexOf(filterName) !== -1 && item.price >= filterMinPrice && item.price <= filterMaxPrice }) } }
在这个方法中,我们首先将用户输入的筛选条件分别提取出来,并将maxPrice和minPrice转换为数字类型。然后,我们使用JavaScript数组的filter方法,从商品列表中筛选出符合条件的商品。可以看到,我们使用了itemName.indexOf(filterName) !== -1这种方式,即通过JavaScript中字符串的indexOf方法来检查itemName是否包含了filterName这个子串。如果包含,则返回true,表示该商品符合筛选条件;否则返回false,表示该商品不符合筛选条件。最后,我们将筛选结果存储到filteredGoodsList中。
- 实现列表渲染
我们可以通过v-for指令来遍历filteredGoodsList数组,并将每个数组元素渲染成一个商品信息块。具体实现代码如下:
<div v-for="(item, index) in filteredGoodsList" :key="index" class="goods-item"> <div class="goods-name">{{ item.name }}</div> <div class="goods-price">{{ item.price }}</div> <div class="goods-stock">{{ item.stock }}</div> <div class="goods-buy-btn" v-show="item.stock > 0">购买</div> <div class="goods-sold-out" v-if="item.stock == 0">已售罄</div> </div>
在这个代码中,我们将v-for指令绑定到filteredGoodsList数组上,这样就可以遍历这个数组中的所有元素。我们使用: key="index"来为每个元素设置一个唯一的key值,以便Vue能够高效地对列表进行更新。
在每个商品信息块中,我们使用v-show和v-if指令来根据不同的商品库存信息来动态展示不同的元素。如果该商品库存大于0,则会显示购买按钮;否则,会显示“已售罄”的文字提示。
- 实现筛选表单和筛选按钮
最后,我们需要在页面上添加一个筛选表单,让用户可以输入不同的筛选条件来观察不同的商品信息。表单的代码如下:
<div class="filter-form"> <label for="filter-name">商品名称:</label> <input type="text" id="filter-name" v-model="filterForm.name"> <label for="filter-min-price">价格区间:</label> <input type="text" id="filter-min-price" placeholder="最小价格" v-model="filterForm.minPrice"> - <input type="text" id="filter-max-price" placeholder="最大价格" v-model="filterForm.maxPrice"> <button @click="filterGoodsList">筛选</button> </div>
在这个代码中,我们使用了v-model指令将表单元素和Vue实例中的filterForm对象绑定在一起,从而实现了双向数据绑定。我们还添加了一个筛选按钮,在用户点击按钮时会触发filterGoodsList方法,从而重新进行商品列表的筛选和渲染。
六、总结
通过以上分析和实例演示,我们了解了Vue文档中的条件渲染函数的基本知识和使用方法,以及v-if和v-show指令在渲染开销、初始化渲染开销和渲染性能等方面的不同表现。最后,我们还运用条件渲染函数的知识,实现了一个商品列表及其筛选功能的实例。相信这些内容能够对您学习和使用Vue框架提供一些帮助。
The above is the detailed content of Analysis of conditional rendering function examples in Vue documents. For more information, please follow other related articles on the PHP Chinese website!

Vue.js is loved by developers because it is easy to use and powerful. 1) Its responsive data binding system automatically updates the view. 2) The component system improves the reusability and maintainability of the code. 3) Computing properties and listeners enhance the readability and performance of the code. 4) Using VueDevtools and checking for console errors are common debugging techniques. 5) Performance optimization includes the use of key attributes, computed attributes and keep-alive components. 6) Best practices include clear component naming, the use of single-file components and the rational use of life cycle hooks.

Vue.js is a progressive JavaScript framework suitable for building efficient and maintainable front-end applications. Its key features include: 1. Responsive data binding, 2. Component development, 3. Virtual DOM. Through these features, Vue.js simplifies the development process, improves application performance and maintainability, making it very popular in modern web development.

Vue.js and React each have their own advantages and disadvantages, and the choice depends on project requirements and team conditions. 1) Vue.js is suitable for small projects and beginners because of its simplicity and easy to use; 2) React is suitable for large projects and complex UIs because of its rich ecosystem and component design.

Vue.js improves user experience through multiple functions: 1. Responsive system realizes real-time data feedback; 2. Component development improves code reusability; 3. VueRouter provides smooth navigation; 4. Dynamic data binding and transition animation enhance interaction effect; 5. Error processing mechanism ensures user feedback; 6. Performance optimization and best practices improve application performance.

Vue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.

Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software