vue2.x watch
<template>
<h2>求和:{{ sum }}</h2>
<button @click="sum++">++</button>
</template>
<script>
import { ref } from "vue";
export default {
watch: {
sum(newval, oldval) {
console.log(newval, oldval);
},
},
setup() {
const sum = ref(0);
return {
sum,
};
},
};
</script>
正常打印,说明vue3中也可以使用vue2.x的写法 完整写法就是带有配置项的
<template>
<h2>求和:{{ sum }}</h2>
<button @click="sum++">++</button>
</template>
<script>
import { ref } from "vue";
export default {
watch: {
sum: {
immediate:true,
deep:true,
handler(ewval, oldval) {
console.log(newval, oldval);
},
},
},
setup() {
const sum = ref(0);
return {
sum,
};
},
};
</script>
vue3.0 watch vue3中的watch是一个函数,所以需要单独引入
<template>
<h2>求和:{{ sum }}</h2>
<button @click="sum++">++</button>
</template>
<script>
import { ref, watch } from "vue";
export default {
setup() {
const sum = ref(0);
watch(sum, (newval, oldval) => {
console.log("vue3.0", newval, oldval);
});
return {
sum,
};
},
};
</script>
以上演示了监听单个ref响应式数据,现在演示监听多个,比较简单的写法就是用两个watch
<template>
<h2>求和:{{ sum }}</h2>
<button @click="sum++">++</button>
<hr />
<h2>招呼:{{ info }}</h2>
<button @click="info += '!'">打招呼</button>
</template>
<script>
import { ref, watch } from "vue";
export default {
setup() {
const sum = ref(0);
const info = ref("hello");
watch(sum, (newval, oldval) => {
console.log("求和", newval, oldval);
});
watch(info, (newval, oldval) => {
console.log("招呼:", newval, oldval);
});
return {
sum,
info,
};
},
};
</script>
<template>
<h2>求和:{{ sum }}</h2>
<button @click="sum++">++</button>
<hr />
<h2>招呼:{{ info }}</h2>
<button @click="info += '!'">打招呼</button>
</template>
<script>
import { ref, watch } from "vue";
export default {
setup() {
const sum = ref(0);
const info = ref("hello");
watch([sum, info], (newval, oldval) => {
console.log("新值newval", newval);
console.log("旧值oldval", oldval);
});
return {
sum,
info,
};
},
};
</script>
immediate,deep配置如下,
<template>
<h2>求和:{{ sum }}</h2>
<button @click="sum++">++</button>
<hr />
<h2>招呼:{{ info }}</h2>
<button @click="info += '!'">打招呼</button>
</template>
<script>
import { ref, watch } from "vue";
export default {
setup() {
const sum = ref(0);
const info = ref("hello");
watch(
sum,
(newval, oldval) => {
console.log("求和", newval, oldval);
},
{ immediate: true}
);
return {
sum,
info,
};
},
};
</script>
|