Vue学习笔记【7】——Vue指令之v-model和双向数据绑定

v-model是唯一可以实现双向数据绑定的vue指令

单向数据绑定:修改内存中的数据,页面上同步更改。v-bind

   <!-- 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">

简易计算器案例

  1. HTML 代码结构

 <div id="app">

    <input type="text" v-model="n1">

    <select v-model="opt">

      <option value="0">+</option>

      <option value="1">-</option>

      <option value="2">*</option>

      <option value="3">÷</option>

    </select>

    <input type="text" v-model="n2">

    <input type="button" value="=" v-on:click="getResult">

    <input type="text" v-model="result">

  </div>

   2.Vue实例代码:

// 创建 Vue 实例,得到 ViewModel

    var vm = new Vue({

      el: '#app',

      data: {

        n1: 0,

        n2: 0,

        result: 0,

        opt: '0'

      },

      methods: {

        getResult() {

          switch (this.opt) {

            case '0':

              this.result = parseInt(this.n1) + parseInt(this.n2);

              break;

            case '1':

              this.result = parseInt(this.n1) - parseInt(this.n2);

              break;

            case '2':

              this.result = parseInt(this.n1) * parseInt(this.n2);

              break;

            case '3':

              this.result = parseInt(this.n1) / parseInt(this.n2);

              break;

          }

        }

      }

    });

  

猜你喜欢

转载自www.cnblogs.com/superjishere/p/11886853.html