zoukankan      html  css  js  c++  java
  • 我的Vue朝圣之路2

    1.创建第一个Vue案例

       1. 引入Vue.js
       2. 创建Vue对象
          el : 指定根element(选择器)
          data : 初始化数据(页面可以访问)
      3. 双向数据绑定 : v-model
      4. 显示数据 : {{xxx}}
      5. 理解vue的mvvm实现

    <div id="test">
      <input type="text" v-model="msg">
      <p>{{msg}}</p>
    </div>
    
    <script type="text/javascript">
    new Vue({
    el: '#test',
    data: {
    msg: 'helloVue'
    }
    })
    </script>
    

      

    2.列表

       1. 在data中初始数组数据
       2. 在页面中遍历显示: v-for
           数据: [
                    {id : 1, name : '张三'},
                    {id : 2, name : '李四'},
                    {id : 3, name : '王五'}
                ]

    <div id="app">
      <ul>
        <li v-for="(todo, index) in todos">{{index+1}}----{{todo.id+'+++'+todo.name}}</li>
      </ul>
    </div>
    
    
    <script type="text/javascript">
      new Vue({
        el: '#app',
        data: function () {
    
          return {
            todos: [
              {id : 2, name : '张三'},
              {id : 3, name : '李四'},
              {id : 5, name : '王五'}
            ]
          }
        }
      })
    </script>

    3.事件

       1. 绑定监听的指令:
           v-on:xxx="函数名或函数调用"
          @xxx="函数名或函数调用"
       2. 定义事件处理的函数:
           methods : {
                函数名 : function(){...}
             }

    <div id="app"><!--就是mvvm中的view-->
      <p>{{msg}}</p>
      <!--<button v-on:click="reverse">倒序</button>-->
      <button @click="reverse">倒序</button>
    </div>
    
    <script type="text/javascript">
      new Vue({ // vm对象
        el : '#app',
        data : { // 一般数据  model对象
          msg: 'I Love You!'
        },
        methods: { // 事件回调函数
          reverse () {
            //this是Vue实例对象
            this.msg = this.msg.split('').reverse().join('')
          }
        }
      })
    </script>

    3.综合使用

      1. 页面指令:
          v-model
         @click
         @keyup.enter
         v-for / $index
         v-text
      2. Vue对象
          初始化数据: data
          事件处理函数: methods

    <div id="app">
      <input type="text" v-model="inputTodo" @keyup.enter="addTodo">
      <ul>
        <li v-for="(todo, index) in todos">
          {{todo.name}}
          <button @click="removeTodo(index)">X</button>
        </li>
      </ul>
    </div>
    
    <script type="text/javascript">
      new Vue({
        el : '#app',
        data : {
          inputTodo: '',
          todos: [
            {id : 2, name : '吃饭'},
            {id : 3, name : '睡觉'},
            {id : 5, name : '打豆豆'}
          ]
        },
        methods : {
          addTodo () {
            // 判断是否是正常输入
            var inputTodo = this.inputTodo.trim()
            if(!inputTodo) {
              return
            }
            // 根据输入创建todo对象
            var todo = {
              id: Date.now(),
              name: inputTodo
            }
            // 添加到todos
            this.todos.unshift(todo)
            // 清除输入数据
            this.inputTodo = ''
          },
          removeTodo (index) {
            this.todos.splice(index, 1)
          }
        }
      })
    </script>

    4.模板语法

      1. 表达式 :
          语法: {{exp}} 或 {{{exp}}}
          功能: 向页面输出数据
          可以调用对象的方法
      2. 强制数据绑定:
          完整写法:
          v-bind:xxx='yyy' //yyy会作为表达式解析执行
          简洁写法:
          :xxx='yyy'
      3. 事件监听:
          完整写法:
          v-on:keyup='xxx'
          v-on:keyup='xxx(参数)'
          v-on:keyup.enter='xxx'
          简洁写法:
         @keyup='xxx'
         @keyup.enter='xxx'

    <div id="app">
    
      <h2>1. 表达式</h2>
      <p>{{message}}</p>
      <p>{{message.toUpperCase()}}</p>
      <h2>2. 强制数据绑定:</h2>
      <a :href="url">跳转</a>
    
      <h2>3. 事件监听:</h2>
      <input type="text" @keyup.enter="test">
      <input type="text" @keyup.enter="test2($event, 'abc')">
    
      <!--模板页面自动去vm对象中找属性-->
    </div>
    
    <script type="text/javascript">
      var vm = new Vue({
        el : '#app',
        data : {
          message: 'atguigu.com',
          url: 'http://www.xxxx.com'
        },
        methods : {
          test (event) {
            alert(event.target.value)
          },
          test2 (event, msg) {
            alert(event.target.value + '----'+msg)
          }
        }
      })
      console.log(vm) // 数据代理(vm代理data中数据的操作(读/写))
      vm.message = "xfzhang"

    5.计算属性

       计算属性
            1. 在computed属性对象中定义计算属性的方法
            2. 在页面中使用{{方法名}}来显示计算的结果
       监视属性:
           1. 通过通过vm对象的$watch()或watch配置来监视指定的属性
           2. 当属性变化时, 回调函数自动调用, 在函数内部进行计算
      计算属性高级:
          1. 通过get/set方法实现对属性数据的显示和监视
          2. 计算属性存在缓存, 多次读取只执行一次

    <div id="demo">
      姓: <input type="text" placeholder="First Name" v-model="firstName"><br>
      名: <input type="text" placeholder="Last Name" v-model="lastName"><br>
      姓名1(单向): <input type="text" placeholder="Full Name" v-model="fullName1">--{{fullName1}}<br>
      姓名2(单向): <input type="text" placeholder="Full Name" v-model="fullName2"><br>
      姓名3(双向): <input type="text" placeholder="Full Name2" v-model="fullName3"><br>
    </div>
    
    <script type="text/javascript">
      var vm = new Vue({
        el : '#demo',
        data : {
          firstName: '上官',
          lastName: '婉儿',
          fullName2: '上官-婉儿'
        },
        computed: {
          fullName1 () { // 相当于只是指定了get
            console.log('fullName1()')
            return this.firstName + '-' + this.lastName
          },
          fullName3: {
            get () {// 获取当前属性值, 当读取当前属性值时回调
              return this.firstName + '-' + this.lastName
            },
            set (value) { // 监视当前属性值的变化, 当属性值发生变化时调用
              var names = value.split('-')
              this.firstName = names[0]
              this.lastName = names[1]
            }
          }
        },
    
        watch: {
          firstName (value) {
            // 更新fullName2
            this.fullName2 = value + '-' + this.lastName
          }
        }
      })
    
      // 监视lastName
      vm.$watch('lastName', function (value) {
        // 更新fullName2
        this.fullName2 = this.firstName + '-' + value
      })
    </script>

    6.class与style绑定

       动态绑定class
          :class="a" a是一个data属性
          :class="{ 'class-a': isA, 'class-b': isB }" 其中isA/isB是布尔型data属性
          :class="[classA, classB]" 其中classA/classB是字符串值
      动态绑定style
          :style="{ color: activeColor, fontSize: fontSize + 'px' }" 其中activeColor/fontSize是data属性

    <div id="demo">
      <p class="classB" :class="a">测试v-bind:class 变量语法</p>
      <p :class="{classA:isA, classB:isB}">测试v-bind:class 对象语法</p>
      <p :class="['classA', classB]">测试v-bind:class 数组语法</p>
    
      <p :style="{ color: activeColor, fontSize: fontSize + 'px' }">测试v-bind:style</p>
    </div>
    
    <script type="text/javascript">
      new Vue({
        el : '#demo',
        data : {
          a: 'classA',
          isA: false,
          isB: true,
          classB: 'classB',
          activeColor: 'green',
          fontSize: 30
        }
      })
    </script>

    7.条件渲染

        切换一个元素:
            v-if
            v-else
            v-show
       切换多个元素
           <template v-if="ok"> //不能用v-show
       注意:
          如果需要频繁切换 v-show 较好,如果在运行时条件不大可能改变 v-if 较好

    <div id="demo">
      <h1>测试: 切换一个元素</h1>
      <p v-if="ok">aaaaa</p>
      <p v-else>bbbbbb</p>
    
      <p v-show="ok">sssssss</p>
    
      <h1>测试: 切换多个元素</h1>
    
      <template v-if="ok">
        <h2>xxxx</h2>
        <h2>yyyy</h2>
        <h2>zzzzz</h2>
      </template>
    
      <button @click="ok=!ok">切换</button>
    </div>
    
    <script type="text/javascript">
      new Vue({
        el : '#demo',
        data : {
          ok: false
        }
      })
    </script>

    8.列表渲染

       1. 遍历显示数组 : v-for / index
       2. 遍历显示对象 : v-for / key

    <div id="demo">
    
      <h2>测试: v-for 遍历数组</h2>
      <ul>
        <li v-for="(p, index) in filterPersons">
          {{index}}--{{p.name}}--{{p.age}}
          --<button @click="removeP(p)">删除</button>
          --<button @click="updateP(p, {name:'Cot', age:18})">更新</button>
        </li>
      </ul>
      <h2>测试: v-for 遍历对象</h2>
      <ul>
        <li v-for="(value, key) in persons[1]">
          {{key}}----{{value}}
        </li>
      </ul>
    </div>
    
    <script type="text/javascript">
      new Vue({
        el : '#demo',
        data : {
          persons: [
            {name: 'Tom', age: 12},
            {name: 'Jack', age: 15},
            {name: 'Bob', age: 14}
          ]
        },
    
        methods: {
          removeP (p) {
            // 得到元素在数组中下标
            var index = this.persons.indexOf(p)
            // 删除
            this.persons.splice(index, 1)
          },
          updateP (oldP,newP) {
            // 得到元素在数组中下标
            var index = this.persons.indexOf(oldP)
            console.log(index)
            // 更新下标所对应的数组元素
            // this.persons[index] = newP
            this.persons.splice(index, 1, newP)
          }
        },
    
        computed: {
          filterPersons () {
            // 哪些数组元素会放入返回的数组中? 只有回调函数返回值为true的p
            return this.persons.filter(p => p.name.indexOf('o')>=0)
          }
        }
      })
    </script>

    9.方法与事件处理器

      1. 绑定监听:
          v-on:xxx="fun"
          @xxx="fun"
          @xxx="fun(参数)"
          默认事件形参: event
          隐含属性对象: $event
      2. 事件修饰符:
          .prevent : 阻止事件的默认行为 event.preventDefault()
          .stop : 停止事件冒泡 event.stopPropagation()
      3. 按键修饰符
          .keycode : 操作的是某个keycode值的健
          .enter : 操作的是enter键

    <div id="example">
    
      <h2>1. 绑定监听</h2>
      <button v-on:click="test1">测试1</button>
      <button @click="test1">测试2</button>
      <button @click="test2('abc', $event)">测试3</button>
    
      <h2>2. 事件修饰符</h2>
      <!--阻止事件的默认行为-->
      <p><a href="http://baidu.com" @click.prevent="test3">百度</a></p>
      <!--停止事件冒泡-->
      <div style="background: red; 300px;height: 300px" @click="test4">
        <div style="background: yellow; 200px;height: 200px" @click.stop="test5"></div>
      </div>
    
      <h2>3. 按键修饰符</h2>
      <input type="text" @keyup.enter="test6">
      <input type="text" @keyup.65="test6">
    </div>
    
    <script type="text/javascript">
      new Vue({
        el : '#example',
        data : {
    
        },
        methods : {
          test1 (event) {
            alert(event.target.innerHTML)
          },
          test2 (msg, event) {
            alert(msg + '---' + event.target.innerHTML)
          },
          test3 () {
            alert('点击链接')
          },
          test4 () {
            alert('点击了外部div')
          },
          test5 () {
            alert('点击了内部div')
          },
          test6(event) {
            alert(event.keyCode + '---' + event.target.value)
          }
        }
      })
    </script>

    10.表单控件绑定

        1. 使用v-model对表单项数据双向绑定
            text/textarea
            checkbox : 绑定boolean/string值
            radio
            select
       2. 失去焦点才更新: .lazy
       3. 自动去除两端空格: .trim

    <div id="demo">
      <input type="text" v-model="msg"><br>
      <textarea cols="30" rows="5" v-model="msg"></textarea>
      <p>{{msg}}</p>
    
      <hr>
      <input type="checkbox" v-model="ok"> {{ok}}<br>
      <input type="checkbox" name="students" value="Tom" v-model="selectStudents">TOM
      <input type="checkbox" name="students" value="Jack" v-model="selectStudents">JACK
      <input type="checkbox" name="students" value="Bob" v-model="selectStudents">BOB
      {{selectStudents}}
      <hr>
    
      <input type="radio" name="sex" value="male" v-model="sex"><input type="radio" name="sex" value="female" v-model="sex">女
      {{sex}}
      <hr>
    
      <select name="city" v-model="selectCityId">
        <option :value="city.id" v-for="city in citys">{{city.name}}</option>
      </select>
      {{selectCityId}}
      <hr>
    
      <input type="text" placeholder="失去焦点才同步数据" v-model.lazy="msg2">{{msg2}}
      <input type="text" placeholder="自动trim" v-model.trim="msg3">---{{msg3}}---
    </div>
    
    <script type="text/javascript">
      new Vue({
        el : '#demo',
        data : {
          msg: 'atguigu',
          ok: true,
          selectStudents: ['Jack'],
          sex: 'female',
          citys: [
            {id: 1, name: 'BJ'},
            {id: 3, name: 'SZ'},
            {id: 5, name: 'SH'}
          ],
          selectCityId: 3,
          msg2: '',
          msg3: ''
        }
      })
    </script>
  • 相关阅读:
    2 初学函数,求幂指数练手程序
    1 批量生成虚拟姓名
    Python 中 time 模块与 datetime 模块在使用中的不同之处
    feature selection&feature abstraction降维
    拿到样本简单的清洗操作
    使用sklearn做单机特征工程
    tensorflow安装
    PCA数学角度解析
    使用Python进行描述性统计【解决了实习初期的燃眉之急】
    类、对象、属性、方法、类的成员
  • 原文地址:https://www.cnblogs.com/MingQiu/p/11065827.html
Copyright © 2011-2022 走看看