0
点赞
收藏
分享

微信扫一扫

初步探索vue3之vue3中不一样的watch

雪域迷影 2022-01-20 阅读 69

vue3(3.0.4)中watch 使用

1. watch监听 ref 定义的响应式数据

setup() {
		let name = ref("张三");
		
        
		watch(name, (newValue, oldValue) => {
			console.log(newValue, oldValue);
		});

		return {
			name,
		};
	},

2.watch监听 ref 定义的多个响应式数据

setup() {
		let name = ref("张三");
        let msg = ref('hello')
		

		watch([name,msg], (newValue, oldValue) => {
			console.log(newValue, oldValue);
		});

		return {
			name,
            msg
		};
	},
或者 vue3可以同时出现多个watch
setup() {
		let name = ref("张三");
        let msg = ref('hello')
        
		watch(name, (newValue, oldValue) => {
			console.log(newValue, oldValue);
		});
		
		watch(msg, (newValue, oldValue) => {
			console.log(newValue, oldValue);
		});

		return {
			name,
            msg
		};
	},

3.watch监听 reactive 定义的响应式数据的全部属性

setup(props) {
		let name = ref("张三");
        let msg = ref('hello')
		let obj = reactive({
			a: 18,
			b: {
				c: {
					d: 23,
				},
			},
			g: 25
		});

		watch(name, (newValue, oldValue) => {
			console.log(newValue, oldValue);
		});
		watch(msg, (newValue, oldValue) => {
			console.log(newValue, oldValue);
		});

		watch(obj, (newValue, oldValue) => {
            console.log('obj已经变化了');
			console.log(newValue, oldValue);
		},{deep:false});

		return {
			name,
			obj,
            msg
		};
	},

4.watch监听 reactive 定义的多个响应式数据的某个属性

watch(()=>obj.a, (newValue, oldValue) => {
			console.log(newValue, oldValue);
			//obj已经变化了
			//Proxy {age: 19} Proxy {age: 19}
		});
watch(()=>obj.b, (newValue, oldValue) => {
			console.log(newValue.c.d, oldValue.c.d);
		},{deep:true});

5.watch监听 reactive 定义的多个响应式数据的某些属性

watch([()=>obj.a,()=>obj.g], (newValue, oldValue) => {
			console.log(newValue, oldValue);
			//obj已经变化了
			//Proxy {age: 19} Proxy {age: 19}
		});
举报

相关推荐

0 条评论