vue3--学习技术胖笔记----第三波 watch监听
作者:互联网
watch就是监听某个变量是否有变化,变化后就执行对应的操作
<template>
<div>
<a href="https://vitejs.dev" target="_blank"></a>
<H2>欢迎光临红浪漫洗浴中心</H2>
<div>请选择一位美女</div>
<button
v-for="(item,index) in girls"
v-bind:key="index"
@click="selectGirlFun(index)"
>
{{index}}:{{item}}
</button>
<div>你选择了【{{selectGirl}}】为你服务</div>
<button @click="overAction">点餐完毕</button>
<div>{{overText}}</div>
</div>
</template>
<script lang="ts">
import {
reactive,
toRefs,
ref,
watch,
} from "vue";
// 接口定义下面各种类型 (规范,不写页面也可以运行,因为没有申明类型ts会默认类型推断)
interface DataProps{
girls: string[];
selectGirl: string;
selectGirlFun:(index:number)=>void
}
export default({
name:"APP",
setup(){
const data=reactive({
girls:["大脚","刘颖","小红"],
selectGirl:"",
selectGirlFun :(index:number)=>{
data.selectGirl=data.girls[index];
}
});
//使用toRefs 让变量和 方法可以在模版直接调用
const refData=toRefs(data)
const overText=ref("红浪漫")
const overAction =()=>{
overText.value="点餐完成 |"+overText.value
}
// // 监听单个值的方法
// watch(overText,(newValue,oldValue)=>{
// console.log(`new----->${newValue}`)
// console.log(`new----->${oldValue}`)
// document.title=newValue;
// })
// 监听多个值的方法
//监听json里面的值要()=>不然前端还有警告提示
watch([overText,()=>data.selectGirl],(newValue,oldValue)=>{
console.log(`new----->${newValue}`) //数组[overText,data.selectGirl] 展示
console.log(`new----->${oldValue}`)
document.title=newValue[0];
})
return{
...refData,
overText,
overAction,
}
},
});
</script>
<style scoped>
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vue:hover {
filter: drop-shadow(0 0 2em #42b883aa);
}
</style>
https://www.bilibili.com/video/BV1L5411j7vj?p=9&vd_source=caabcbd2a759a67e2a3de8acbaaf08ea
标签:--,data,watch,监听,----,overText,selectGirl,newValue 来源: https://www.cnblogs.com/kaibindirver/p/16683324.html