iT邦幫忙

2025 iThome 鐵人賽

DAY 14
0
Vue.js

Vue.js 新手入門之路系列 第 14

Vue.js 新手入門之路 - 雙向綁定(二)

  • 分享至 

  • xImage
  •  

延續昨日的雙向綁定
我們也可以搭配 v-for 來渲染選單的 options

<template>
    <div class="box">
        <select v-model="selected" multiple>
            <option v-for="option in options" :value="option.value">
                {{ option.text }}
            </option>
        </select>

        <p>selected: {{ selected }}</p>
    </div>
</template>

<script setup>
    import { ref } from 'vue'
    const selected = ref('[]')
    const options = ref([
        { text: '香蕉', value: 'banana' },
        { text: '蘋果', value: 'apple' },
        { text: '葡萄', value: 'grape' }
    ])
</script>

select 預設單選,我們加上 multiple 關鍵字就可以變為多選
https://ithelp.ithome.com.tw/upload/images/20250903/201782964qoRBUjGKy.png

v-model 通常用來綁定靜態文字或布林值(複選框),但我們可以透過搭配使用 v-bind 來使其綁定動態或是非文字類型的資料
以下是綁定物件的例子

<template>
    <div class="box">
        <input type="checkbox" v-model="checked" :value="1"> 數字 1
        <input type="checkbox" v-model="checked" :value="{id:2}"> 物件
        <p>{{ checked }}</p>
    </div>
</template>

<script setup>
import { ref } from 'vue'
const checked = ref([])
</script>

https://ithelp.ithome.com.tw/upload/images/20250903/20178296njqZkdG8Bl.png

toggle 預設布林值,也就是 truefalse

<input type="checkbox" v-model="toggle">

true-valuefalse-value 是 Vue 給的特定 attribute,只能搭配 v-model 使用,這邊透過這兩個特定屬性把換成綁定字串

<input
  type="checkbox"
  v-model="toggle"
  true-value="yes"
  false-value="no"
/>

同樣可以透過 v-bind 動態綁定,數值、物件、陣列都可以

<input
  type="checkbox"
  v-model="toggle"
  :true-value="dynamicTrueValue"
  :false-value="dynamicFalseValue"
/>

當然如果嫌麻煩,想在 v-model 直接綁定非字串類型的資料也是可以的

<template>
    <div class="box">
        <select v-model="selected">
            <option :value="{ name: 'Dog',age:10 }">dog</option>
            <option :value="{ name: 'Cat',age:5 }">cat</option>
        </select>
        <p>{{ selected }}</p>
    </div>
</template>

<script setup>
import { ref } from 'vue'
const selected = ref({})
</script>

這邊直接綁定物件
https://ithelp.ithome.com.tw/upload/images/20250903/201782964QqRy3wCHI.png

v-model 的修飾子

  • .lazy
  • .number
  • .trim

一般情況下 v-model 在輸入時就同步會更新變數, .lazy 會改成只在 change 事件(輸入框失焦或按 Enter)才更新,適合用在只在輸入完畢後再更新的狀況

<input v-model.lazy="msg" />

通常 input 就算輸入數字也是屬於數字字串,這時 .number 可以幫我們把輸入值使用 parseFloat() 轉換為浮點數型態,當使用 input[type="number"] 時,.number 會自動啟用

<input v-model.number="age" />

最後是 .trim 可以移除 user 輸入的前後空白,適合用在避免 user 輸入多餘空格,例如帳號、密碼

<input v-model.trim="msg" />

ref:
https://zh-hk.vuejs.org/guide/essentials/forms.html


上一篇
Vue.js 新手入門之路 - 雙向綁定
下一篇
Vue.js 新手入門之路 - Watchers
系列文
Vue.js 新手入門之路17
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言