<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue侦听器</title>
</head>
<body>
<div id="app">
<!-- 案例1 -->
<div id="watch-example">
<p>
Ask a yes/no question:
<input v-model="question">
</p>
<p>{{ answer }}</p>
</div>
<!-- 案例2 -->
<div>
<span>姓</span>
<input type="text" v-model="last" />
</div>
<div>
<span>名</span>
<input type="text" v-model="first" />
</div>
<span>结果:{{fullName}}</span>
<!-- 案例3 -->
<div>
<!-- 这种验证不可能每次字符变动去就执行。所以这里我们要加一个
lazy:将input事件切换为change事件(输入框失去焦点.才进行双向绑定) -->
<input type="text" v-model.lazy="uname" />
{{tip}}
</div>
</div>
</body>
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript">
var vm = new Vue({
el: "#app",
data: {
question: '',
last:'w',
first:'b',
/* fullName:'wb', */
answer: 'I cannot give you an answer until you ask a question!',
tip:'',
uname:''//准备验证的用户名
},
//计算属性
//计算属性和方法最大的区别
//计算属性是基于它们的依赖进行缓存的
//方法不存在缓存
//计算属性的值就不要在data里面定义了。这样就会出现重复定义
computed: {
fullName: function() {
return this.last+' '+this.first;
}
},
//方法
methods:{
checkName:function(name){
//调用API接口进行name验证
//当前用一个定器模拟验证
var that=this
that.tip='正在验证中'
setTimeout(function(){
if(name=='admin') that.tip='已经存在了'
else that.tip='可以使用'
},2000)
}
},
//侦听器的应用场景
//数据变化时异步或者开销较大的操作
watch: {
// 如果 `question` 发生改变,这个函数就会运行
question: function(newQuestion, oldQuestion) {
console.log(newQuestion+'question发生了改变'+oldQuestion)
this.answer = 'Waiting for you to stop typing...'
},
//正常情况加一个侦听器监听姓名两个值的变动情况
/* last:function(value){
console.log('当前姓:'+value)
this.fullName=value+""+this.first;
},
first:function(value){
console.log('当前名:'+value)
this.fullName=this.last+value;
} */
uname:function(value){
this.checkName(value);
}
}
})
</script>
</html>