1、常用的用法
<template>
<div id="app">
<input type="text" v-model="val" />
<div>{{message}}</div>
</div>
</template>
<script>
export default {
name:"App",
data(){
return{
val:"",
message:""
}
},
watch:{
val(newVal){
this.message = newVal;
}
}
}
</script>
<style lang="scss">
</style>
2、绑定方法
<template>
<div id="app">
<input type="text" v-model="val" />
<div>{{message}}</div>
</div>
</template>
<script>
export default {
name:"App",
data(){
return{
val:"",
message:""
}
},
watch:{
val:"changeMessage"
},
methods: {
changeMessage(newVal){
this.message = newVal;
}
},
}
</script>
<style lang="scss">
</style>
3、深度监听
<template>
<div id="app">
<input type="text" v-model="val.a.b" />
<div>{{message}}</div>
</div>
</template>
<script>
export default {
name:"App",
data(){
return{
val:{
a:{
b:""
}
},
message:""
}
},
watch:{
val:{
handler:"changeMessage",
deep:true
}
},
methods: {
changeMessage(newVal){
this.message = newVal.a.b;
}
},
}
</script>
<style lang="scss">
</style>
4、初始化自动执行一次
<template>
<div id="app">
<input type="text" v-model="val.a.b" />
<div>{{message}}</div>
</div>
</template>
<script>
export default {
name:"App",
data(){
return{
val:{
a:{
b:"46456"
}
},
message:""
}
},
watch:{
val:{
handler:"changeMessage",
immediate:true
}
},
methods: {
changeMessage(newVal){
this.message = newVal.a.b;
}
},
}
</script>
<style lang="scss">
</style>
5、绑定多个handler
<template>
<div id="app">
<input type="text" v-model="val" />
<div>{{message}}</div>
</div>
</template>
<script>
export default {
name:"App",
data(){
return{
val:"",
message:""
}
},
watch:{
val:[{
handler:"changeMessage"
},"changeMessage2",function(newVal){
this.message = this.message + "func";
}]
},
methods: {
changeMessage(newVal){
this.message = newVal;
},
changeMessage2(newVal){
this.message = this.message + "changeMessage2";
}
},
}
</script>
<style lang="scss">
</style>
6、监听属性变化
<template>
<div id="app">
<input type="text" v-model="val.a.b" />
<div>{{message}}</div>
</div>
</template>
<script>
export default {
name:"App",
data(){
return{
val:{
a:{
b:""
}
},
message:""
}
},
watch:{
"val.a.b":"changeB"
},
methods: {
changeB(newVal){
this.message = newVal;
}
},
}
</script>
<style lang="scss">
</style>