前段时间本人一塌糊涂,迷失了自我,整个人乌七八糟,心神不宁,失魂落魄,感觉非常焦虑。放假从新调整了本人,当初的我干劲十足,十分精力。从新开启我的学习之路。gogogogogogogogo!!!!!!!!!!!!!!!!!
先说需要,咱们想在选车实现之后新增一个“抉择结束”的按钮,弹出抉择的是什么车,同时把浏览器title改成:”您抉择的是XXX”,话不多说,间接上代码
<template>
<div class="about">
<button @click="selectFun(car)" v-for="(car, index) in cars" :key="index">
{{ car }}
</button>
<div>抉择的是{{ selectCar }}</div>
<hr />
<div><button @click="overAction">选车结束</button></div>
<div>{{ overText }}</div>
</div>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, toRefs, watch } from "vue";
export default defineComponent({
name: "about",
setup() {
const data = reactive({
cars: ["EVO", "STI", "GTR"],
selectCar: "",
selectFun: (car: string) => {
data.selectCar = car;
},
});
const refData = toRefs(data);
const overText = ref("");
const overAction = () => {
// 这个中央须要留神,不实用reactive,赋值须要.value
// 每次点击后对overText进行赋值并在watch中进行监听进行相干操作
overText.value = "您抉择的是" + data.selectCar;
};
// watch须要先在下面进行援用,overText变换后,赋值给title
watch(overText, (newV) => {
document.title = newV;
});
return {
...refData,
overText,
overAction,
};
},
components: {},
});
</script>
<style lang="scss" scoped>
.about {
margin-top: 80px;
}
</style>
看一下成果,当初始化时
咱们抉择一个车,而后点击“选车结束”按钮
能够看到咱们的watch
监听器起作用了
然而我vue2
中是能够对多个data,或者计算属性进行监听的,那么在vue3
中咱们如何实现了。
在vue3中是这样实现的
watch([overText, data.selectCar], (newV) => {
console.log(newV);
document.title = newV[0];
});
发现报错了,它通知咱们能够用一个函数解决reactive
中的值的问题。把程序写成这个上面的样子就不报错了。
watch([overText, () => data.selectCar], (newV) => {
console.log(newV);
document.title = newV[0];
});
咱们页面上的两个按钮看一下浏览器的控制台
当初程序就能够失常运行了,有人会说Vue3不能监听reactive
里边的值是不是一个Bug,我想说的这并不是Bug,而是为了放弃和Vue2的一致性,因为在Vue2中也时这种后果,解决方案是要么是ref
或者这种get/set
办法的模式。要么你你开启设置watchOptions
的deep为true,也就是深度监听模式。
发表回复