Vue3中的watch和computed的使用方法详解

IT 文章7天前更新 小编
0 0 0

现在很多web前端项目开使用vue3开发,而对潘老师这中专注于Java后端开发的程序员而言,之前也只学过vue2.x,现在是前后端兼顾,最近有个功能要用到watch监听器和computed计算属性,但是用法和vue2还是有区别的,下面潘老师对Vue3中的watch和computed的使用方法做下记录,方便以后使用。

computed使用

// 模板代码


// vue代码
import { computed } from 'vue'
export default {
  setup() {
    const num = 1
    const nextNum = computed(() => {
      return num + 1
    })
    return { 
      num,
      nextNum
    }
  }
}

watch侦听器使用

import { watch} from 'vue'
export default ({
	setup () {
		// 监听一个复杂数据类型 reactive
		const state = reactive({ count: 0 });
		watch(() => state.count, (newCount, oldCount) => {
			console.log(newCount, oldCount);
		});
		// 直接监听一个简单数据类型 ref
		const count = ref(0);
		watch(count, (newCount, oldCount) => {
			console.log(newCount, oldCount);
		});
	} 
})

以上就是Vue3中对于watch和computed的使用方法,成功地解决了潘老师的问题,特此记录,以备不时之需!

© 版权声明

相关文章

暂无评论

暂无评论...