---
tags: Vue 實戰班
---
# v-model
說明:用於表單的資料與元件產生雙向綁定
注意:`v-model` 會忽略所有表單元素的 `value`、`checked`、`selected` 特性的初始值而總是將 Vue 實例的數據作為數據來源。需透過 JavaScript 在元件的 `data` 選項中宣告初始值。
範例重點:
- 將 v-model 與 data 中的 `message` 綁定
- 此為雙向綁定,當 v-model 中的 message 值改變時,畫面上的 `{{ message }}` 也會一起更動
<iframe height="300" style="width: 100%;" scrolling="no" title="v-model-1" src="https://codepen.io/Wcc723/embed/dyBvmbY?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true">
See the Pen <a href="https://codepen.io/Wcc723/pen/dyBvmbY">
v-model-1</a> by Casper (<a href="https://codepen.io/Wcc723">@Wcc723</a>)
on <a href="https://codepen.io">CodePen</a>.
</iframe>
## v-model 修飾符:
此修飾符是搭配 v-model 使用,與 v-on 的觸發器略有不同,用來延遲觸發、改變型別、修飾字串等等
### lazy
`lazy`:避免持續性觸發,可以在編輯完後才觸發資料更新(使用 change 的形式進行同步)
範例重點:
- v-model 後方加上 `.lazy` 修飾符
- 當 input 編輯時,無法直接修改畫面上的值,需要離開 input 時才會觸發
<iframe height="300" style="width: 100%;" scrolling="no" title="Vue lazy" src="https://codepen.io/Wcc723/embed/vYqxRBK?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true">
See the Pen <a href="https://codepen.io/Wcc723/pen/vYqxRBK">
Vue lazy</a> by Casper (<a href="https://codepen.io/Wcc723">@Wcc723</a>)
on <a href="https://codepen.io">CodePen</a>.
</iframe>
### number
`number`:限制只有數值型別的資料才能寫入,以下範例中的 number 資料會是以 `number` 型別傳入,無法透過該 input 套用其它資料型別。
範例重點:
- 無論 input type 為何,input 預設所傳入的型別為字串
- 可以使用 .number 的修飾符,確保用戶所輸入的為純數值
<iframe height="300" style="width: 100%;" scrolling="no" title="v-model-3" src="https://codepen.io/Wcc723/embed/RwzpMbG?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true">
See the Pen <a href="https://codepen.io/Wcc723/pen/RwzpMbG">
v-model-3</a> by Casper (<a href="https://codepen.io/Wcc723">@Wcc723</a>)
on <a href="https://codepen.io">CodePen</a>.
</iframe>
### trim
3. `trim`:修飾掉首尾的空白
範例重點:
- 用戶在輸入文字時,可能會在結尾補上空白,使用 `.trim` 修飾符則會移除結尾的空白字元
<iframe height="300" style="width: 100%;" scrolling="no" title="v-model-4" src="https://codepen.io/Wcc723/embed/OJepvLg?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true">
See the Pen <a href="https://codepen.io/Wcc723/pen/OJepvLg">
v-model-4</a> by Casper (<a href="https://codepen.io/Wcc723">@Wcc723</a>)
on <a href="https://codepen.io">CodePen</a>.
</iframe>