您的位置:首頁技術文章
文章詳情頁

Vue 的 v-model用法實例

瀏覽:35日期:2022-10-24 11:40:53

Vue 框架早已經不是 MVVM(Mode-View-View-Model) 雙向綁定了。早在 Vue 1.0 時代,Vue 在剛出世的時候的確是 MVVM 雙向綁定。自 Vue 2.0 以來,Vue 就不再是雙向綁定了,而是像 React 一樣是單向綁定 MV(Model-View)了。但是,在 Vue 中仍保留了雙向綁定的接口,v-model 就是。

1. 基本用法

<template> <div id='app'> <input v-model='x'> {{x}} </div></template><script>export default { data(){ return { x: ’init’ } }}

在 JS 中修改 x 的值,input 輸入框里也會隨之改變。同樣地,在頁面中的 input 輸入框內手動輸入值,變量 x 的值也會隨之改變。對象里的變量改變會影響視圖的 input 的改變,視圖中 input 的改變會影響對象里變量 x 值的改變。這就是雙向綁定(Model-View-View-Model)。

2. v-model

實質上述使用 v-model 的代碼等價于如下代碼:

<template> <div id='app'> <input :value='x' @input='x = $event.target.value'> {{x}} </div></template><script>export default { data(){ return { x: ’init’ } }}</script>

v-model 幫我們做的事就是,為 input 的 value 值設置一個動態綁定,然后在輸入框的 input 事件觸發后實時修改動態綁定的 value 的變量值。因此 v-model 實質是上述方式的語法糖。

$event 是原生 DOM 事件里的 event 事件對象。

3. v-model 的修飾符

所有修飾符都是起一個輔助的作用,其實可以在函數里自己判斷條件實現。.lazyv-model 默認監聽的是輸入框的input 事件,原生 DOM 的input 事件就是記錄實時的輸入變化值。但是,我們有時不需要實時記錄結果,只需要記錄最終輸入的結果值就可以了。

input 的原生 DOM 事件中還有一個change 事件,該事件是在輸入框失去焦點時 或 按下回車鍵時 執行的。v-model 里以.lazy 修飾符的方式切換至該監聽模式。

<template> <div id='app'> <input v-model.lazy='x'> {{x}} </div></template>等價于:<template> <div id='app'> <input :value='x' @change='x = $event.target.value'> {{x}} </div></template>

.number.number修飾符是在輸入內容改變后進行變量賦值時,自動使用 parseFloat() 函數將其變成數字。使用該修飾符時變量的初始值必須是數字。

<template> <div id='app'> <input v-model.number='x'> {{x}} </div></template><script>export default { data(){ return { x: 0 } }}</script> .trim

.trim修飾符是將輸入的內容改變后進行變量賦值時,自動忽略和去除前后的空格。更為精準地記錄輸入的字符串內容。

<template> <div id='app'> <input v-model.trim='x'> {{x}} </div></template><script>export default { data(){ return { x: ’init’ } }}</script>

4. 自定義輸入框的 v-modelv-model

的基本用法僅僅適用于原生的輸入框元素 ,對于用戶自己封裝的輸入框,可以用如下方式使用 v-model。當用在組件上時,v-model 的實質如下:

<custom-input v-model='x'></custom-input>等價于:<custom-input :value='x' @input='x = $event'></custom-input>

因此,在自定義表單組件里的寫法如下:

<template> <div class='wrapper'> <input :value='value' @input='$emit(’input’, $event.target.value)'> </div></template><script>export default { props: { value: { type: String } }}</script><style scoped> .wrapper{ border: 2px solid blue; display: inline-block; } .wrapper input{ color: red; }</style><template> <div id='app'> <MyInput v-model='x'/> {{x}} </div></template><script>import MyInput from ’./components/MyInput’export default { data(){ return { x: 0 } }, components:{ MyInput }}</script>

補充:若想在自定義組件里面的原生輸入框也使用 v-model,可以根據組件 v-model 的實質,使用計算屬性的賦值方式為=使用。

以上就是Vue 的 v-model用法實例的詳細內容,更多關于vue v-model的資料請關注好吧啦網其它相關文章!

標簽: Vue
相關文章:
国产综合久久一区二区三区