joken-前端工程师

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: :: 管理 ::

示例代码

<!-- vue 模板中使用临时变量测试示例 -->
<template>
    <div class="component-name">
        <!-- vue模板中循环定义临时变量实现 -->
        <div v-for="item in items" :key="item.id" :data-item="(itemTemp = formatter(item))">
            <div>{{ itemTemp.name }}</div>
            <div>{{ itemTemp.formattedPrice }}</div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from 'vue';
//需要在这里初始化那个临时变量,这样模板才能访问到,不至于报错变量未定义找不到之类的
const itemTemp: { [k: string]: any } = {};
// 定义初始数据
const items = reactive([
    { id: 1, name: 'Apple', price: 1.5 },
    { id: 2, name: 'Banana', price: 0.8 },
    { id: 3, name: 'Orange', price: 1.2 }
]);

function formatter(item) {
    // 格式化数据
    return { ...item, formattedPrice: item.price * 10 };
}
</script>

<style lang="scss" scoped></style>

posted on 2024-07-30 22:32  joken1310  阅读(442)  评论(0)    收藏  举报