[Vue3] 基础总结下-计算属性computed,watch监听,ShowRef

142 阅读1分钟

image.png

P10 计算属性

<template>
	<div>
            <h1>computed计算属性介绍:</h1>
            <div>
                    马云年龄: 
                    <input type="text" v-model="my">
            </div>
            <div>
                    马化腾年龄:
                    <input type="text" v-model="ht">
            </div>
            <div>
                    年龄总和: 
                    <input type="text" :value="sum">
            </div>
	</div>
</template>

<script>
import { computed, reactive, toRefs } from "vue";
export default ({
	setup() {
            const my = '0';
            const ht = '0';
            const res = reactive({my, ht})

            const sum = computed(() => {
                    return Number(res.my) + Number(res.ht)
            })

            return {...toRefs(res), sum}
	}
})	
</script>

<style>
</style>

P10-watch 监听

<template>
	<div>
		<h1>{{p1}}</h1>
		<button  @click="p1++">点击++</button>
		
		<h1>响应式对象监听: {{obj.age.number}}</h1>
		<button  @click="obj.age.number++">点击++</button>
	</div>
</template>

<script setup>
	import {reactive, ref, watch} from 'vue'
	const p1 = ref(0)
	const obj = reactive({
		name:"张三",
		age: {
			number: 30
		}
	})
	
	// j监听REF数据变化
	watch(p1, (newVal, oldVal) => {
		console.log(newVal, oldVal);
	})
	
	watch(()=>obj.age.number, (newVal, oldVal) => {
		console.log(newVal, oldVal);
	})
</script>