zl程序教程

您现在的位置是:首页 >  前端

当前栏目

vue3条件渲染v-if与列表渲染v-for 与微信小程序对比

Vue3列表微信程序 for 对比 条件 if
2023-09-11 14:19:18 时间

vue3条件渲染v-if与列表渲染v-for 与微信小程序对比

一、条件渲染v-if

  • v-if 使用
  • template 使用
  • v-show使用
  • v-if 与 v-show区别
<template>
    <!--v-if在微信相当 wx.if-->
    <p v-if="score >= 90">优秀</p>
    <p v-else-if="score >= 80">良好</p>
    <p v-else-if="score >= 60">合格</p>
    <p v-else>不合格</p>

    <!--template在微信相当block-->
    <template v-if="true">
        <h3>整体内容</h3>
        <h3>整体内容</h3>
    </template>

    <!--v-show 操作css的display-->
    <p v-show="sex == 'man'"></p>
    <p v-show="sex == 'woman'"></p>

    <!--v-if与v-show区别-->
    <!--v-show在元素始终会被渲染并保留在DOM中,频繁切换状态使用-->
    <!--v-if在元素会创建和销毁,在运行时,很少改变,一次性-->
    <p v-if="isShow">v-if</p>
    <p v-show="!isShow">v-show</p>
    <button @click="isShow = !isShow">v-if 与 v-show 区别</button>
</template>

<script setup>
import { ref, reactive } from 'vue'
const score = ref(59)
const sex = ref('man')
const isShow = ref(true)
</script>

其中 频繁切换 用 v-show

  • show在元素始终会被渲染并保留在DOM中,频繁切换状态使用
  • v-if在元素会创建和销毁,在运行时,很少改变,一次性

微信小程序wx:if,wx:elif,wx:else

<view wx:if={{score>=90}}>优秀</view>
<view wx:elif={{score>=80}}>良好</view>
<view wx:elif={{score>=60}}>合格</view>
<view wx:else>不合格</view>

微信小程序 block

<block wx:if="true">
	<view>...内容...</view>
</block>

二、列表渲染v-for

  • v-for 使用数组
  • item 代表数组中每一个元素
  • index 表示数组元素的下标
<template>
    <!--key是item-->
    <ul>
        <li v-for="item in arr" :key="item">
            {{ item }}
        </li>
    </ul>
    
    <!--key是index-->
    <ul>
        <li v-for="(item, index) in arr" :key="index">
            {{ item }}-->{{ index }}
        </li>
    </ul>
    
    <!--item.name-->
    <ul>
        <li v-for="(item, index) in arr0" :key="index">
            {{ item.name }}-->{{ index }}
        </li>
    </ul>
    
    <!--嵌套数组-->
    <ul v-for="(nums, index) in arr1" :key="index">
        <p>{{ 'index:' + index }}</p>
        <li v-for="num in even(nums)">
            {{ num }}
        </li>
    </ul>
</template>

<script setup>
import { ref} from 'vue'

const arr = ref(['a', 'b', 'c', 'd', 'e'])
const arr0 = ref([{ name: 'a' }, { name: 'b' }, { name: 'c' }])
const arr1 = ref([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

//筛选数组中的偶数
function even(numbers) {
    return numbers.filter(number => number % 2 === 0)
}
</script>
  • 微信小程序 for渲染
  • wx:for=“{{arr}}”
  • wx:for-item=“item” 默认可不写,表示元素
  • wx:for-index=“index” 默认可不写,表示下标
  • wx:key=“id” 或 *this