v-model指令介紹
怎麼實現動態的在M和V之間數據傳遞呢,本文我們就來介紹下v-model這個非常有用的指令
v-bind 和 v-model 指令的使用
前面的文章中我們已經介紹過了v-bind指令,該指令可以獲取vue對象中的數據,但是這個指令只能實現 M 到V的數據傳遞,反過來實現不了,如下:
<!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>
<script src="./lib/vue-2.4.0.js"></script>
</head>
<body>
<div id="app">
信息:<input type="text" name="" v-bind:value="msg" style="width: 200px">
<hr/> 信息2:
<input type="text" name="" v-model:value="msg2" style="width: 200px">
</div>
<script>
var vm = new Vue({
el: "#app",
data: {
msg: "波波烤鴨,加油鴨...",
msg2: "c336699,1加油鴨..."
},
methods: {
}
})
</script>
</body>
</html>
簡易計算器實現
利用我們講的v-model指令來實現一個簡單的計算器效果。代碼如下:
<!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>
<script src="./lib/vue-2.4.0.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model="n1">
<select v-model="opt">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" v-model="n2">
<input type="button" value="=" @click="calc">
<input type="text" v-model="result">
</div>
<script>
// 創建 Vue 實例,得到 ViewModel
var vm = new Vue({
el: '#app',
data: {
n1: 0,
n2: 0,
result: 0,
opt: '+'
},
methods: {
calc() { // 計算器算數的方法
// 邏輯:
/* switch (this.opt) {
case '+':
this.result = parseInt(this.n1) + parseInt(this.n2)
break;
case '-':
this.result = parseInt(this.n1) - parseInt(this.n2)
break;
case '*':
this.result = parseInt(this.n1) * parseInt(this.n2)
break;
case '/':
this.result = parseInt(this.n1) / parseInt(this.n2)
break;
} */
// 注意:這是投機取巧的方式,正式開發中,儘量少用
var codeStr = 'parseInt(this.n1) ' + this.opt + ' parseInt(this.n2)'
this.result = eval(codeStr)
}
}
});
</script>
</body>
</html>