<template>
<h1>{{ msg }}</h1>
<button @click="counter++">counter is: {{ counter }}</button>
<p>
{{ doubleCounter }}
</p>
<p ref="desc"></p>
</template>
<script>
import {
computed,
onMounted,
onUnmounted,
reactive,
ref,
toRefs,
watch,
} from "vue";
export default {
name: "HelloWorld",
props: {
msg: String,
},
setup() {
// counter相关
const { counter, doubleCounter } = useCounter();
// ref:单值相应式
const msg2 = ref("some message");
// 使用元素引用
const desc = ref(null);
// 侦听器
watch(counter,(val,oldVal)=>{
const p = desc.value
p.textContent = `counter change from ${oldVal} to ${val}`
});
return { counter, doubleCounter, msg2, desc };
},
};
function useCounter() {
// counter相关
// reactive:复合类型
const data = reactive({
counter: 1,
doubleCounter: computed(() => data.counter * 2),
});
let timer;
// 页面加载
onMounted(() => {
timer = setInterval(() => {
data.counter++;
}, 1000);
});
// 页面离开
onUnmounted(() => {
clearInterval(timer);
});
// 解构data
return toRefs(data);
}
</script>
vue3学习笔记一:ref、reactive、toRefs、watch、computed的使用
最新推荐文章于 2023-01-06 16:56:22 发布