Vue指令之v-model
<body>
<div id="app">
<h4>{{ msg }}</h4>
<!-- v-bind 只能實現數據的單向綁定,從 M 自動綁定到 V, 無法實現數據的雙向綁定 -->
<!-- <input type="text" v-bind:value="msg" style="width:100%;"> -->
<!-- 使用 v-model 指令,可以實現 表單元素和 Model 中數據的雙向數據綁定 -->
<!-- 注意: v-model 只能運用在 表單元素中 -->
<!-- input(radio, text, address, email....) select checkbox textarea -->
<input type="text" style="width:100%;" v-model="msg">
</div>
<script>
// 創建 Vue 實例,得到 ViewModel
var vm = new Vue({
el: '#app',
data: {
msg: '大家都是好學生,愛敲代碼,愛學習,愛思考,簡直是完美,沒瑕疵!'
},
methods: {
}
});
</script>
</body>
簡易計算器實現
<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>