关于vue3 ref数据被公用的问题?

现在在一个地方点击更改loading状态,然后所有的组件的loading状态都被改变了,这个好像有点像是vue2 的 data 没有返回函数。
在vue2中可以

data() { return { loading: false } }


请问在vue3中应该怎么解决?谢谢解答,文件信息如下

父页面

<template>
    <loading-box class="box1" />
    <loading-box class="box2" />
    <loading-box key="1" />
    我试了,如果加上key也是会出现截图的情况
</template>
<script setup>
import loadingBox  from './loading.vue'
</scrript>

loading-box.vue

<template>
    <div>{{ loading }} 
    <button @click="loading = !loading">更改loading</button></div>
</template>
<script setup>
import { loading } from './public'
</script>

public.ts

import { ref } from 'vue'
export let loading = ref(true)
阅读 1.7k
1 个回答
✓ 已被采纳

通过函数return出去

import { ref } from "vue";

export default function useLoading(initValue = false) {
  const loading = ref(initValue);
  const setLoading = (value) => {
    loading.value = value;
  };
  const toggle = () => {
    loading.value = !loading.value;
  };
  return {
    loading,
    setLoading,
    toggle,
  };
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题