語法格式
語法格式:
v-model="vue_instance_attr"
//value會(huì)自動(dòng)把輸入值賦值給vue實(shí)例的attr字段奥此。
使用示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!--引入最新的vue穩(wěn)定版本-->
<script type="text/javascript" src="https://unpkg.com/vue/dist/vue.min.js"></script>
<link rel="stylesheet" href="./css/style.css" type="text/css">
</head>
<body>
<!--input輸入框-->
<div id="app">
<input type="text" v-model="message" placeholder="請(qǐng)輸入">
<p>輸入的內(nèi)容是: {{message}}</p>
</div>
<script>
var vue=new Vue({
el:'#app',
data:{
message:''
}
});
</script>
</body>
</html>
運(yùn)行結(jié)果:
v-model基本使用
如何理解v-model指令
v-model指令的本質(zhì)是: 它負(fù)責(zé)監(jiān)聽用戶的輸入事件,從而更新數(shù)據(jù)推姻,并對(duì)一些極端場景進(jìn)行一些特殊處理。同時(shí),v-model會(huì)忽略所有表單元素的value醉旦、checked、selected特性的初始值桨啃,它總是將vue實(shí)例中的數(shù)據(jù)作為數(shù)據(jù)來源车胡。 然后當(dāng)輸入事件發(fā)生時(shí),實(shí)時(shí)更新vue實(shí)例中的數(shù)據(jù)照瘾。
實(shí)現(xiàn)原理
<input v-bind:value="message" v-on:input="message = $event.target.value" /> //把input輸入框的value屬性值和vue實(shí)例的message屬性進(jìn)行綁定匈棘,同時(shí)監(jiān)聽輸入事件。
用v-bind和v-on指令實(shí)現(xiàn)v-model
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!--引入最新的vue穩(wěn)定版本-->
<script type="text/javascript" src="https://unpkg.com/vue/dist/vue.min.js"></script>
<link rel="stylesheet" href="./css/style.css" type="text/css">
</head>
<body>
<!--input輸入框-->
<div id="app">
<!--把message字段的值作為input標(biāo)簽的value屬性值网杆,同時(shí)監(jiān)聽輸入事件羹饰,實(shí)時(shí)更新message的值-->
<input type="text" @input="handleInput($event)" placeholder="請(qǐng)輸入" v-bind:value="message">
<p>輸入的內(nèi)容是: {{message}}</p>
</div>
<script>
var vue=new Vue({
el:'#app',
data:{
message:''
},
methods:{
handleInput: function (event) {
console.info("控制臺(tái)打印event詳情")
console.info(event)
console.info(event.toLocaleString());
this.message=event.target.value;
}
}
});
</script>
</body>
</html>
運(yùn)行結(jié)果:
v-bind和v-on實(shí)現(xiàn)v-model指令