v-model实现双向绑定:
代码示例如下:
如上所示改变输入框的值,对应的message也会对应修改
如上所示如果直接修改message的值,输入框的值也会相应修改
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="../js/vue.js"></script>
<div id="app">
<input type="text" v-model="message">
<h2>{{message}}</h2>
</div>
<script>
const app = new Vue({
el: "#app",
data: {
message: "hello ,chen"
}
})
</script>
</body>
</html>
其实上述双向绑定还有其他实现方式,利用v-bind:value绑定input值和v-on:input事件监听input框的值得改变从而设置message的值
当输入框里输入新的值时,@input就会调用changeValue方法,该方法调用时如果不写参数,默认传入一个event事件,event的target对象的value值即是输入的新的值
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="../js/vue.js"></script>
<div id="app">
<input type="text" :value="message" @input="changeValue">
<h2>{{message}}</h2>
</div>
<script>
const app = new Vue({
el: "#app",
data: {
message: "hello ,chen"
},
methods: {
changeValue(event){
console.log(event)
this.message = event.target.value;
}
}
})
</script>
</body>
</html>
还有更简单的写法,不用新增changeValue函数,直接写方法体
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="../js/vue.js"></script>
<div id="app">
<input type="text" :value="message" @input="message = $event.target.value">
<h2>{{message}}</h2>
</div>
<script>
const app = new Vue({
el: "#app",
data: {
message: "hello ,chen"
},
methods: {
// changeValue(event){
// console.log(event)
// this.message = event.target.value;
// }
}
})
</script>
</body>
</html>