Index.vue:
javascript
<script setup>
import { ref, onMounted } from 'vue'
import useList from './useList'
import './index.css'
const indexCount = ref(0)
const { count, handleClick } = useList(indexCount)
const handleIndexCount = () => {
indexCount.value++
}
onMounted(() => {})
</script>
<template>
<div class="m-home-wrap">
<button @click="handleIndexCount">{{ indexCount }}</button>
<button @click="handleClick">{{ count }}</button>
<div class="m-home-demo"></div>
</div>
</template>
<style></style>
useList.js:
javascript
import { ref, onMounted, watchEffect, toValue } from 'vue'
const useList = (props) => {
const count = ref(0)
watchEffect(() => {
let value = toValue(props)
console.log(value)
count.value = value
})
const handleClick = () => {
count.value++
}
onMounted(() => {
console.log(1)
})
return {
count,
handleClick,
}
}
export default useList
watchEffect的作用:
响应式地追踪其依赖
toValue的作用:
toValue()
是一个在 3.3 版本中新增的 API。它的设计目的是将 ref 或 getter 规范化为值。如果参数是 ref,它会返回 ref 的值;如果参数是函数,它会调用函数并返回其返回值
人工智能学习网站