作者:mobiledu2502872907 | 来源:互联网 | 2023-05-30 12:13
watch
比computed灵活
watch中可以执行任何逻辑
函数节流
Ajax异步数据
操作DOM
重点:依赖固定数据类型(响应式数据)
通过vm(Vue实例)对象的$watch()或watch配置来监视指定的属性
当属性变化时候,回调函数自动调用,在函数内部进行计算
<template><div><label>姓:<input type&#61;"text" placeholder&#61;"firstName" v-model&#61;"firstName"/></label><p></p><label>名:<input type&#61;"text" placeholder&#61;"lastName" v-model&#61;"lastName"/></label><p>单向</p><label>姓名:<input type&#61;"text" placeholder&#61;"fullName" v-model&#61;"fullName"/></label><p>双向</p><label>姓名:<input type&#61;"text" placeholder&#61;"fullName" v-model&#61;"fullNameup"/></label><p>watch监视方法</p><label>姓名:<input type&#61;"text" placeholder&#61;"fullName" v-model&#61;"fullnamewatch"/></label></div>
</template><script scoped>
export default {name: "Testtwo",data() {return {firstName: "",lastName: "",fullnamewatch: "",};},
watch: {firstName(value) {console.log(&#96;watch监视到firstName发生改变:${value}&#96;);this.fullnamewatch &#61; value &#43; "." &#43; this.lastName;},lastName(value) {console.log(&#96;watch监视到lastName发生改变:${value}&#96;);this.fullnamewatch &#61; this.firstName &#43; "." &#43; value;},},
};
</script><style scoped>
</style>
app设置
<template><div><Testtwo /></div>
</template><script>
import Testtwo from "./components/Testtwo";
export default {name: "App",components: {Testtwo,},
};
</script><style scoped>
#app {font-family: Avenir, Helvetica, Arial, sans-serif;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;text-align: center;color: #2c3e50;margin-top: 60px;
}
</style>
或者用下面这个没有注释之前的代码
<template><div><label>姓:<input type&#61;"text" placeholder&#61;"firstName" v-model&#61;"firstName"/></label><p></p><label>名:<input type&#61;"text" placeholder&#61;"lastName" v-model&#61;"lastName"/></label><p>单向</p><label>姓名:<input type&#61;"text" placeholder&#61;"fullName" v-model&#61;"fullName"/></label><p>双向</p><label>姓名:<input type&#61;"text" placeholder&#61;"fullName" v-model&#61;"fullNameup"/></label><p>watch监视方法</p><label>姓名:<input type&#61;"text" placeholder&#61;"fullName" v-model&#61;"fullnamewatch"/></label></div>
</template><script scoped>
export default {name: "Testtwo",data() {return {firstName: "",lastName: "",fullnamewatch: "",};},computed: {fullName: {get() {return this.firstName &#43; "." &#43; this.lastName;},},fullNameup: {get() {console.log(&#96;调用了getter的方法&#96;);return this.firstName &#43; "." &#43; this.lastName;},set(value) {console.log(&#96;调用了setter的方法&#96;);let names &#61; value.split(".");console.log(names);this.firstName &#61; names[0];this.lastName &#61; names[1];},},},watch: {firstName(value) {console.log(&#96;watch监视到firstName发生改变:${value}&#96;);this.fullnamewatch &#61; value &#43; "." &#43; this.lastName;},lastName(value) {console.log(&#96;watch监视到lastName发生改变:${value}&#96;);this.fullnamewatch &#61; this.firstName &#43; "." &#43; value;},},
};
</script><style scoped>
</style>