我们的差值表达式是无法在标签属性栏中使用的,这也就意味着,我们无法给某些文本框之类的直接预设值. eg:如下是不行的
姓名:<input type="text" id="username" value="user.username"><br>
密码:<input type="password" id="password" value="user.password"><br>
姓名:<input type="text" id="username" value={{user.username}}><br>
密码:<input type="password" id="password" value={{user.password}}><br>
//view model
new Vue({
el:"#app",
data:{
user:{
name:"zyh",
pw:"123"
}
}
})
使用如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>v-if与v-show</title>
<script src="js/vuejs-2.5.16.js"></script>
</head>
<body>
<div id="app">
<form>
用户名:<input type="text" id="username" v-model="user.name" /><br />
密 码:<input type="password" id="password" v-model="user.pw" />
</form>
</div>
</body>
<script>
//view model
new Vue({
el:"#app",
data:{
user:{
name:"zyh",
pw:"123"
}
}
})
</script>
</html>
效果:
另外这个在我们做一些选项绑定也特别有用,比如对于复选框的checkbox和单选的radio.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="app">
<div id="example-1">
<input v-model="message" placeholder="edit me">
<p>Message is: {{ message }}</p>
<textarea v-model="message2" placeholder="add multiple lines"></textarea>
<p style="white-space: pre-line;">{{ message2 }}</p>
<br />
<div style="margin-top:20px;">
<input type="checkbox" id="jack" value="Jack" v-model="checkedNames">
<label for="jack">Jack</label>
<input type="checkbox" id="john" value="John" v-model="checkedNames">
<label for="john">John</label>
<input type="checkbox" id="mike" value="Mike" v-model="checkedNames">
<label for="mike">Mike</label>
<br>
<span>Checked names: {{ checkedNames }}</span>
</div>
<div style="margin-top:20px;">
<input type="radio" id="one" value="One" v-model="picked">
<label for="one">One</label>
<br>
<input type="radio" id="two" value="Two" v-model="picked">
<label for="two">Two</label>
<br>
<span>Picked: {{ picked }}</span>
</div>
<button type="button" @click="submit">提交</button>
</div>
</div>
<script type="text/javascript">
var vm = new Vue({
el : "#app",
data : {
message : "test",
message2 :"hi",
checkedNames : [],
picked : "Two"
},
methods: {
submit : function () {
console.log(this.message);
}
}
});
</script>
<style type="text/css">
</style>
</body>
</html>
v-model双向绑定,选择效果图如图
此外,V-model提供了一些修饰符