关于vue3响应式更新的疑问?
例如我创建了一个dataHook
import { ref } from 'vue';
export function dataHook() {
const v = ref(1);
return {
v
};
}
main.ts
中
const app = createApp(App);
const { v } = dataHook();
app.mount('#app');
setTimeout(() => {
console.log(v);
}, 5000);
页面有个按钮就执行v.value += 1
,为什么console.log
还是原值1
呢?
<Button @click="onClickO">点击hook {{ v }}</Button>
<script setup lang="ts">
import { dataHook } from '@/utils/data';
const { v } = dataHook();
function onClickO() {
v.value += 1;
}
</script>
回复
1个回答

test
2024-06-27
跟 Vue 无关,而是很基础的 JS 语法问题。
先直接抛开 Vue,你现在是三个文件对吧?
// shared.js
export function getFoo() {
const foo = new Foo();
return { foo };
}
// a.js
import { getFoo } from './shared';
const { foo } = getFoo();
// b.js
import { getFoo } from './shared';
const { foo } = getFoo();
问:此时 a.js 里的 foo
,跟 b.js 里的 foo
,是同一个对象实例吗?
答:不是,这两个文件里分别调用的 getFoo()
,里面都是新 new 出来的,当然是两个对象实例。
再问:那么怎样可以让 a.js 和 b.js 共享同一个对象?
再答:得把它提出来啊:
// shared.js
const foo = new Foo();
export function getFoo() {
return { foo };
}
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容