vue3 ref/监听/计算属性

<script setup>
import {
	ref,
	reactive,
	computed,
	watch,
	watchEffect,
	onBeforeMount,
	onMounted,
	onBeforeUpdate,
	onUpdated,
	onBeforeUnmount,
	onUnmounted
} from 'vue';

onBeforeMount(() => {
	console.log('onBeforeMount');
});
const input = ref(null);
onMounted(() => {
	console.log('onMounted');
	// input.value.focus();
});
onBeforeUpdate(() => {
	console.log('onBeforeUpdate');
});
onUpdated(() => {
	console.log('onUpdated');
	console.log(
		document.getElementById('count').textContent
	);
});
onBeforeUnmount(() => {
	console.log('onBeforeUnmount');
});
onUnmounted(() => {
	console.log('onUnmounted');
});

defineProps({
	msg: String,
	msg1: String
});

const count = ref(0);
const count1 = reactive(1);
console.log(count, 'count');

// 只读计算属性
const computedValue = computed(() => {
	return count1 > 0 ? '2' : '3';
});
console.log(computedValue, 'computedValue');

// 可写计算属性
const firstName = ref('zhang');
const lastaName = ref('chao');
const fullName = computed({
	get() {
		// 计算/返回值
		return firstName.value + ' ' + lastaName.value;
	},
	set(newValue) {
		[firstName.value, lastaName.value] = newValue.split(
			' '
		);
	}
});
console.log(fullName.value);

// 监听器
const watcher = ref('');

// 可以直接侦听一个 ref
watch(watcher, async (newWatcher, oldWatcher) => {
	console.log(newWatcher);
	console.log(oldWatcher);
});

const count2 = ref(1);
// 监听一个getter函数 只能是ref
watch(
	() => count.value + count2.value,
	sum => {
		console.log(`${sum}`, 'sum');
	}
);

const obj = reactive({
	count3: 0
});
watch(
	() => obj.count3,
	count3 => {
		console.log(count3, '3');
	}
);
watchEffect(() => {
	if (input.value) {
		input.value.focus();
	} else {
		console.log('dom null');
	}
});
</script>

<template>
	<h1>{{ msg }}</h1>
	<h1>{{ msg1 }}</h1>
	<p>{{ computedValue }}</p>
	<p>{{ fullName }}</p>
	<button id="count" @click="count++">{{ count }}</button>
	<br />
	<input v-model="watcher" ref="input" />
</template>

<style scoped></style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值