vue3学习之侦测变化watch

我爱海鲸 2023-10-16 18:11:32 前端

简介侦测变化watch

链接上一篇文章:vue3学习之生命周期

一个简单的问题,我页面启动的时候title会进行绑定,当时当页面变化的时候tilte却不会改变了,那是因为setup只执行一次,那么如何侦测变化呢,我们可以使用watch函数来进行侦测。

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <h1>{{count}}</h1>
    <h1>{{double}}</h1>
    <ul>
      <li v-for="number in numbers" :key="number">
        <h1>{{number}}</h1>
      </li>
    </ul>
    <h1>{{person.name}}</h1>
    <button @click="increase">赞+1</button><br/>
    <button @click="updateGreeting">Update Title</button>
  </div>
</template>

<script lang="ts">
  // 响应式对象引入,计算函数引入
import { ref,computed,reactive,toRefs,onMounted,onUpdated,watch } from 'vue'

interface DataProps {
  count: number;
  double: number;
  increase: () => void;
  numbers: Array<number>,
  person: {name ? :string}
}

export default{
  name: 'App',
  setup() {
    onMounted(() => {
      console.log('onMounted');
    })
    onUpdated(() => {
      console.log('onUpdated');
    })
    // onRenderTracked((event) => {
    //   console.log(event);
    // })

    const data: DataProps  = reactive({
      count: 0,
      increase: () => { data.count++},
      double: computed(() => data.count * 2),
      numbers: [0,1,2],
      person: {}
    })
    const greetings = ref('')
    const updateGreeting = () => {
      greetings.value += 'Hello! '
    }
    watch([greetings,()=> data.count], (newValue,oldValue) => {
      console.log('old',oldValue)
      console.log('new',newValue)
      document.title = 'update' + greetings.value + data.count
    })
    data.numbers[0] = 5;
    data.person.name = 'haijin';
    const refData = toRefs(data)
    return {
      ...refData,
      greetings,
      updateGreeting
    }
  }
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

 

总结,watch是监控响应式变化的一个函数

2023-10-16 start:

	const nationValue = ref('')
	
	watch(nationValue,(newValue,oldValue)=>{
		      console.log('old',oldValue)
		      console.log('new',newValue)
	})

end

 

你好:我的2025