vue中setup函数里面使用侦听器watch侦听普通字符串和对象

32 阅读1分钟

使用侦听器watch的时候,如果是普通类型语法如下

watch("侦听对象",{
()=>{侦听后触发的逻辑}
})

如果被侦听的是对象,被侦听的对象要写成函数的形式,语法如下

watch(
()=>{"被侦听的对象"},
()=>{“侦听后触发的逻辑”}

)

如果侦听的是一个普通数字类型,代码如下

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="root"></div>
  </body>
  <script>
    const app = Vue.createApp({
      // setup函数
      setup() {
      //引入vue方法
        const { ref, watch } = Vue;
       
       //响应式引用,需要用ref包起来
        const inputValue = ref("111111");
        // 使用侦听器,监听inputValue的变黄
        // 里面2个参数,第一个是要侦听谁,第二个是一个箭头函数,侦听的对象发生改变就触发
        watch(inputValue, (currentValue, prevValue) => {
          console.log(
            `侦听器正在执行,inpuValue的值从${prevValue}变成了${currentValue}`
          );
        });
        return { inputValue };
      },
      // 模板
      template: `
        <h1>{{inputValue}}</h1>
        <input type="text" v-model="inputValue"  />
        `,
    });
    const vm = app.mount("#root");
  </script>
</html>

如果侦听的是一个对象

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="root"></div>
  </body>
  <script>
    // setup函数
    const app = Vue.createApp({
      // setup函数
      setup() {
        const { reactive, watch,toRefs } = Vue;
        const userObj = reactive({
          username: "zhangsan",
        });
        // 侦听器
        watch(
          () => userObj.username,
          (currentValue, prevValue) => {
            console.log(`
                触发了侦听对象,从${prevValue}变成了${currentValue}
                `);
          }
        );
        // 用结构赋值的方式把定义好的username取出来
        // 结构赋值要有动态渲染效果,需要把被结构的用toRefs()包起来
        const { username } = toRefs(userObj);
        return { username };
      },

      //模板
      template: `
        <input type="text" v-model="username" />
        <h1>{{username}}</h1>
        `,
    });

    const vm = app.mount("#root");
  </script>
</html>