Vue中的渲染是对模板的处理。根据BOM+DOM+js的前端组成,Vue的渲染是Vue组件模板根据指令编译,然后挂载到DOM解构中的过程,无论是条件渲染还是列表渲染。
条件渲染相关的指令有:
v-if/v-else/v-else-if/v-show
v-show:组件挂载时就会渲染,css的dispaly属性会根据v-show的值发生变化,适合频繁隐藏/显示切换的HTML片段。
v-if:组件会根据v-if的值确定挂载时要不要渲染,如果为false则组件的HTML片段不会进入渲染过程。频繁隐藏/显示切换的HTML片段不适合使用它。
列表渲染的指令有:
v-for
v-for:有多种表现形式,但是有非常标准的推荐格式。
<script setup lang="ts">
import {computed, nextTick, ref} from "vue"
const count=ref(0);
const list=ref(["a","b","c"]);
list.value[1]="e";
function increment(){
count.value++;
nextTick();
if(count.value>=3){
list.value[count.value]="add";
}
}
//computed attribute
const size=computed(()=>{
return list.value.length;
});
// update class by computed attribute ,more than one class is also allowed.
const currentState=computed(()=>{
return list.value.length%2==0 ? true : false;
});
</script>
<template>
<button @click="increment">{{ count }}</button>
<div v-for="item in list" :key="item">
<span>{{ item }}</span>
</div>
<div v-if="currentState">Hello, World!</div>
<div v-else>I am one!</div>
</template>
<style>
</style>