跳至主要内容

Day1 - Vue.js 的基礎魔法:v-text、v-html、v-once

2025 Vue 直播班每日任務,藉由一天學一點積沙成塔

Topic

操作提供的模版,執行以下要求(只能修改 HTML 的部分):

  1. 操作 class 名稱為 Q1 的 div 標籤,利用 {{ }} 將對應 data 中的資料帶入 HTML 中進行畫面渲染。
  2. 操作 class 名稱為 Q2 的 div 標籤,利用 v-text 將 rawHTML 帶入。
  3. 操作 class 名稱為 Q3 的 div 標籤,利用 v-html 將 rawHTML 帶入。
  4. 操作 class 名稱為 Q4 的 div 標籤,加入 v-once
<template>
<div id="app">
<div class="Q1">
Ray 身上有 ? 元,去超商吃午餐花了 ? 元,買了一杯飲料花了 ? 元
</div>
<div class="Q2"></div>
<div class="Q3"></div>
<div class="Q4">此欄位為單次綁定 {{ lunchPrice }}</div>
</div>
</template>

<!-- 請不要修改下面內容 -->
<script setup>
import { ref } from "vue";
const RayMoney = ref(1500);
const lunchPrice = ref(90);
const drinkPrice = ref(65);
const rawHTML = ref('<p>姆咪姆咪心動動 (*´∀`)~♥</p>');
</script>

Result

<script setup>
import { ref } from "vue";
const inputText = ref('');
</script>
<template>
<div id="app">
<div class="Q1">
Ray 身上有 {{RayMoney}} 元,去超商吃午餐花了 {{lunchPrice}} 元,買了一杯飲料花了 {{drinkPrice}}
</div>
<div class="Q2" v-text="rawHTML"></div>
<div class="Q3" v-html="rawHTML"></div>
<div class="Q4" v-once>此欄位為單次綁定 {{ lunchPrice }}</div>
</div>
<input type="text" v-model="inputText"/>
<div v-text="inputText"></div>
</template>

思考與反饋

  • 學習使用 {{}}v-textv-htmlv-once 及差異
  • 加碼學習了 refv-model 來進行雙向綁定

CODE

連結到 Codepen