前段时间自己一塌糊涂,迷失了自我,整个人乱七八糟,心神不宁,魂不守舍,感觉十分焦虑。放假重新调整了自己,现在的我干劲十足,非常精神。重新开启我的学习之路。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>

看一下效果,当初始化时
alt

alt

我们选择一个车,然后点击“选车完毕”按钮

alt

alt

可以看到我们的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];
    });

我们页面上的两个按钮看一下浏览器的控制台

alt

现在程序就可以正常运行了,有人会说Vue3不能监听reactive里边的值是不是一个Bug,我想说的这并不是Bug,而是为了保持和Vue2的一致性,因为在Vue2中也时这种结果,解决方案是要么是ref或者这种get/set方法的形式。要么你你开启设置watchOptions的deep为true,也就是深度监听模式。