vue3组合式函数如何接收响应式状态

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 的值;如果参数是函数,它会调用函数并返回其返回值

人工智能学习网站

https://chat.xutongbao.top

相关推荐
kyriewen1 分钟前
你等的Babel编译,够喝三杯咖啡了——用Rust重写的SWC,只需眨个眼
前端·javascript·rust
Ww.xh4 分钟前
鸿蒙系统中HTML与Vue集成方案
vue.js·html·harmonyos
搬砖码10 分钟前
同源多标签页通信 4 种方案,从入门到生产环境
前端·面试
张元清14 分钟前
SSR 状态管理陷阱:defineStore vs defineContextStore
前端·javascript·面试
donecoding38 分钟前
nrm、corepack、npm registry 三者的爱恨情仇
前端·node.js·前端工程化
小gaigagi42 分钟前
从吉客云·奇门到MySQL的完整数据流
前端
悟空瞎说44 分钟前
用 Rust 开发 QML 桌面应用(第二篇)—— 日志系统完整搭建
前端
LIO1 小时前
前端开发之Git 代码仓库管理详细教程
前端·git
软件开发技术深度爱好者1 小时前
前端网页开发三剑客快速入门
前端
openKaka_1 小时前
为什么 React 18 之后使用 createRoot,而不是 ReactDOM.render
前端·javascript·react.js