前端与移动开发之vue-day1(2)

Vue指令之v-on的缩写和事件修饰符事件修饰符:
.stop 阻止冒泡
.prevent 阻止默认事件
.capture 添加事件侦听器时使用事件捕获模式
.self 只当事件在该元素本身(比如不是子元素)触发时触发回调
.once 事件只触发一次

Vue指令之v-model和双向数据绑定简易计算器案例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>

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;

          }

        }

      }

    });

在Vue中使用样式使用class样式数组

<h1 :class="{red:true, italic:true, active:true, thin:true}">这是一个邪恶的H1</h1>
1. 数组中使用三元表达式

    <h1 :class="['red', 'thin', isactive?'active':'']">这是一个邪恶的H1</h1>

1. 数组中嵌套对象

    <h1 :class="['red', 'thin', {'active': isactive}]">这是一个邪恶的H1</h1>

1. 直接使用对象

    <h1 :class="{red:true, italic:true, active:true, thin:true}">这是一个邪恶的H1</h1>

使用内联样式

1. 直接在元素上通过 :style 的形式,书写样式对象

    <h1 :style="{color: 'red', 'font-size': '40px'}">这是一个善良的H1</h1>

1. 将样式对象,定义到 data 中,并直接引用到 :style 中

- 在data上定义样式:

    data: {
            h1StyleObj: { color: 'red', 'font-size': '40px', 'font-weight': '200' }
    }

- 在元素中,通过属性绑定的形式,将样式对象应用到元素中:

    <h1 :style="h1StyleObj">这是一个善良的H1</h1>

1. 在 :style 中通过数组,引用多个 data 上的样式对象

- 在data上定义样式:

    data: {
            h1StyleObj: { color: 'red', 'font-size': '40px', 'font-weight': '200' },
            h1StyleObj2: { fontStyle: 'italic' }
    }

- 在元素中,通过属性绑定的形式,将样式对象应用到元素中:

    <h1 :style="[h1StyleObj, h1StyleObj2]">这是一个善良的H1</h1>

猜你喜欢

转载自blog.51cto.com/13517854/2316805