欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

vue3(1)学习

程序员文章站 2022-05-17 20:40:41
...
vue3 学习(1)

reactivecomputed onmounted toRefs onUnmounted watch toRefs ref

<template>
	<div>{{ counter }}</div>
	<div>{{ doublecounter }}</div>
	<p ref="desc"></p>
</template>
import { defineComponent, reactive, toRefs, computed , onMounted ,watch,onUnmounted} from "vue";
import {useRouter} from 'vue-router'
export default defineComponent({
	setup(){
		const state=reactive({
			counter:1
			doublecounter:computed(()=>state.counter*2)
		})
		let timer
		//定时器
		onMounted(()=>{
			timer=setInterval(()=>{
				state.counter++
			},1000)
		})
		//移除定时器
		onUnmounted(()=>{
			clearInterval(timer)
		})
		
		const desc = ref(null)
		//监听器
		watch(state.counter,(val,oldval)=>{
			//p就是desc这个元素
			let p=desc.value
			p.textContent=`counter change from ${oldval} to ${val}`
		})
	return{...toRefs}
	}
})