watch:{
x(){
}
}中的方法名必须跟要监听的data中的属性名一样,才代表监听指定属性
当侦听器监听的属性发生变化时,就会调用watch中对应的方法
侦听器属性,比计算属性计算效率消耗大
new Vue({
el:"",//关联界面元素
data:{x:12},//vm的数据源
methods:{},//方法
filter:{},//过滤器
computed:{xx(){}}, //xx就是一个计算属性
watch:{x(){}} //x就是监听了data中的x属性的一个监听器
})
举例:
向下滑动内容使内容上方的按钮(动态添加)根据滑动到的内容显示选中的颜色
思路:
利用监听器,当内容滑动到一定的高度时就改变指定按钮的背景颜色。注意使用监听器时需要监听的属性与监听函数要同名!
在改变按钮时,怎样定位到按钮呢?可以利用按钮数组的下标定位到按钮
改变指定按钮颜色:将class属性进行绑定,添加一个改变后的的样式类名,并设置为false.监听器监听到后将其设置为true
完整代码:
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>Document</title>
<script src='https://cdn.jsdelivr.net/npm/vue/dist/vue.js'></script>
</head>
<body>
<style>
#app{
width: 800px;
margin: 0 auto;
background-color: aquamarine;
position: relative;
}
.btn{
width: 800px;
display: flex;
justify-content: space-between;
}
.btn button{
width: 100px;
}
.content{
position: absolute;
width: 100%;
height: 400px;
background-color: beige;
overflow: scroll;
}
.content::-webkit-scrollbar { width: 0 !important }
.bgc1{
background-color: blue;
color: aliceblue;
}
</style>
<div id='app'>
<!-- 按钮 -->
<div class="btn" >
<button v-for="(el,index) in arr" :key="el.id" :class="{bgc1:el.flag}">{{el.name}}</button>
</div>
<!-- 内容 -->
<div class="content" @scroll="move">
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
<p>hello</p>
</div>
</div>
<script>
new Vue({
el:'#app',
data: {
// 按钮数组
arr:[{
id:1,
name:"新闻",
flag:true
},{
id:2,
name:"娱乐",
flag:false
},
{
id:3,
name:"财经",
flag:false
},
{
id:4,
name:"军事",
flag:false
}
],
scrollTop:0,
},
methods: {
// 将卷曲高度复制给我们设定的参数中
move(el){
console.log(el.target.scrollTop)
this.scrollTop=el.target.scrollTop
}
},
computed: {},
watch:{
// 通过判断卷曲高度来改变按钮背景
scrollTop(){
console.log(11111)
if(this.scrollTop>=0&&this.scrollTop<184){
// 排他
this.arr.forEach(el => {
el.flag=false
});
this.arr[0].flag=true
}else if(this.scrollTop>=184&&this.scrollTop<=368){
this.arr.forEach(el => {
el.flag=false
});
this.arr[1].flag=true
}else if(this.scrollTop>=368&&this.scrollTop<=552){
this.arr.forEach(el => {
el.flag=false
});
this.arr[2].flag=true
}else {
this.arr.forEach(el => {
el.flag=false
});
this.arr[3].flag=true
}
}
}
})
</script>
</body>
</html>
举例:
实现汇率的转换
完整代码:
<div id='app'>
rmb:<input type="text" v-model="rmb">
dollar:<input type="text" v-model="dollar">
</div>
<script>
new Vue({
el:'#app',
data: {
rmb:0,
dollar:0
},
methods: {},
computed: {},
watch:{
rmb(newvalue,oldvalue){
this.dollar=(newvalue/6.9).toFixed(2)*100/100
},
dollar(newvalue,oldvalue){
this.rmb=(newvalue*6.9).toFixed(2)*100/100
},
}
})
</script>