原文網址:Vue--v-model--使用/教程/實體_IT利刃出鞘的博客-CSDN博客
簡介
說明
本文用示例介紹Vue的v-model指令的用法,
官網
表單輸入系結 — Vue.js
v-model簡介
說明
可以用 v-model 指令在表單 <input>、<textarea> 及 <select> 元素上創建雙向資料系結,它會根據控制元件型別自動選取正確的方法來更新元素,
v-model 本質上是語法糖,它可以自動創建雙向系結:1. 監聽用戶的輸入事件以更新資料 2.資料變動時更新DOM,雙向系結原理見:Vue--雙向系結的原理--手寫雙向系結(模仿vue)_IT利刃出鞘的博客-CSDN博客
v-model獲取的輸入的值和事件
v-model 在內部為不同的輸入元素使用不同的 property 并拋出不同的事件:
- text 和 textarea 元素:使用 value property 和 input 事件;
- checkbox 和 radio:使用 checked property 和 change 事件;
- select:將 value 作為 prop 并將 change 作為事件,
用法
場景1:用在本組件的HTML節點上
<template>
<div class="hello">
<input v-model="msg">
</div>
</template>
<script>
export default {
name: 'Demo',
data () {
return {
msg: 'Hello, Welcome'
}
}
}
</script>
場景2:參考其他組件
<template>
<div class="hello">
<component-b v-model="msg"></component-b>
</div>
</template>
<script>
export default {
name: 'Demo',
data () {
return {
msg: 'Hello, Welcome'
}
}
}
</script>
注意:此處v-model是簡寫,下邊兩個是等價的
<!-- 縮寫 -->
<component-b v-model="value"></component-b>
<!-- 完整語法 -->
<component-b v-bind:value="value" v-on:input="value = $event"></component-b>
示例
代碼
Demo.vue
<template>
<div class="hello">
<input v-model="msg">
<button @click="updateMsg()">更新資料</button>
</div>
</template>
<script>
export default {
name: 'Demo',
data () {
return {
msg: 'Hello, Welcome'
}
},
watch: {
msg(newValue, oldValue) {
console.log('msg=> oldValue: ' + oldValue);
console.log('msg=> newValue: ' + newValue);
}
},
methods: {
updateMsg() {
this.msg = "This is new value";
}
}
}
</script>
<style scoped>
</style>
路由(router/index.js)
import Vue from 'vue'
import Router from 'vue-router'
import Demo from "../views/Demo";
Vue.use(Router)
export default new Router({
routes: [
{
path: '/demo',
name: 'Demo',
component: Demo,
}
],
})
測驗
訪問:http://localhost:8080/#/demo

測驗1:修改輸入的值

測驗2:修改物件的值
點擊“更新資料”

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/413923.html
標籤:其他
