zoukankan      html  css  js  c++  java
  • Vue 侦听器 watch

    1. 侦听器 watch


    Vue 提供了一种更通用的方式来观察和响应 Vue 实例上的数据变动:侦听属性

    当属性发生改变时,自动触发属性对应的侦听器。

    当需要在数据变化时执行异步或开销较大的操作时,这个方式是最有用的。

    2. 基础用法


    当 msg 属性的值发生改变时,就会触发侦听器的执行

    <div id="app">
    	<input type="text" v-model="msg">
    </div>
    <script>
    	let vm = new Vue({
    		el: '#app',
    		data: {
    			msg: 'Hello'
    		},
    		watch: {
    			msg: function(){
    				console.log(this.msg)
    			}
    		}
    	})
    </script>
    

    3. 应用场景:用户注册时,验证用户名是否存在


    <div id="app">
    	用户名: <input type="text" name="name" v-model.lazy="username">
    	<span :style="msgStyle">{{ msg }}</span>
    	<br>
    	密码: <input type="password" name="pass">
    </div>
    <script>
    	let vm = new Vue({
    		el: '#app',
    		data: {
    			msg: '',
    			username: '',
    			msgStyle: ''
    		},
    		watch: {
    			username: function(){
    				// 发送ajax请求 验证用户名
    				if (this.username == 'liang') {
    					this.msg = '该用户名已存在'
    					this.msgStyle = {
    						color: 'red',
    						fontWeight: 'bold'
    					}
    				} else {
    					this.msg = '用户名可以注册'
    					this.msgStyle = {
    						color: 'green',
    						fontWeight: 'bold',
    					}
    				}
    			}
    		}
    	})
    </script>
    
  • 相关阅读:
    Python进阶03 模块
    Python进阶02 文本文件的输入输出
    Python进阶01 词典
    Python基础10 反过头来看看
    Python基础09 面向对象的进一步拓展
    Python基础08 面向对象的基本概念
    Python基础07 函数
    Vuex源码分析(转)
    Vue2.x双向数据绑定
    Angular2的双向数据绑定
  • 原文地址:https://www.cnblogs.com/cfmy/p/13348390.html
Copyright © 2011-2022 走看看