关于前端:Vue3第5课Wacth的使用与注意事项

26次阅读

共计 1557 个字符,预计需要花费 4 分钟才能阅读完成。

前段时间本人一塌糊涂,迷失了自我,整个人乌七八糟,心神不宁,失魂落魄,感觉非常焦虑。放假从新调整了本人,当初的我干劲十足,十分精力。从新开启我的学习之路。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,也就是深度监听模式。

正文完
 0