vue2与vue3中侦听器,Vue3中基础数据一个或多个ref

<template>
  <div id="app">
    <nav>
     <p>vue2与vue3侦听器的区别</p>
     <p>当前数值是: {{count}}</p>
     <button @click="count++">点击++</button>
     <hr>
     <p>当前字符串是: {{str}}</p>
     <button @click="str+='国庆节快乐'">点击改变字
    </nav>

  </div>
</template>
<script>
import { ref, watch } from 'vue'
export default {
  name: 'App',
  //这是vue2的侦听器
  #region vue2侦听器

  data() {
    return {
      count: 0
    }
  },
  watch: {
    这是简洁写的版本,vue2的侦听器
    count(newVal, oldVal) {
      console.log('newVal:', newVal, 'oldVal:', ol
    }   
    这是完整写法的侦听器
    count: {
      handler(newVal, oldVal) {
        console.log('newVal:', newVal, 'oldVal:', 
      },
      deep: true, // 深度侦听
      immediate: true // 立即执行
    }
  },
  #endregion

  //这是vue3的侦听器  ref定义的数据
  setup() {
    const count = ref(0)
    const str=ref('hello')

    //第一咱情况,侦听ref基础数据单一的数据
    // watch(count, (newVal, oldVal) => {
      // console.log('新值:', newVal, '旧值:', old
    // },{//这里可以写其他参数
      // deep: true, // 深度侦听,基础数据没有必要
      // immediate: true // 立即执行 
    // })

     //第二咱情况,对多个ref数据进行侦听
    watch([count,str], (newVal, oldVal) => {
      console.log('新值:', newVal, '旧值:', oldVal
    },{//这里可以写其他参数
      deep: true, // 深度侦听,基础数据没有必要深
      immediate: true // 立即执行 
    })
    return {count,str}
   }
 
  }
</script>
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-seri
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

nav {
  padding: 30px;
}

nav a {
  font-weight: bold;
  color: #2c3e50;
}

nav a.router-link-exact-active {
  color: #42b983;
}
</style>


posted @ 2024-10-01 21:10  一个人走在路上  阅读(24)  评论(0)    收藏  举报