我使用带有组合 API 的 vue3,但是当我构建项目时,ref 元素始终未定义。
我复制了一下,可能是我用错了,但不知道为什么。
const isShow = ref(false)
const rootRef = ref<HTMLDivElement>();
export default function () {
function changeShow() {
isShow.value = !isShow.value;
console.log(isShow.value, rootRef.value);
}
return { isShow, rootRef, changeShow };
}
HelloWorld.vue 和链接元素中使用 rootRef。<script setup lang="ts">
import useShow from "../composables/useShow";
const { rootRef, isShow } = useShow();
</script>
<template>
<div ref="rootRef" v-show="isShow" class="test"></div>
</template>
App.vue中创建按钮并绑定点击函数。<script setup lang="ts">
import HelloWorld from "./components/HelloWorld.vue";
import useShow from "./composables/useShow";
const { changeShow } = useShow();
</script>
<template>
<button @click="changeShow">切换</button>
<HelloWorld />
</template>
当我点击按钮时,它就起作用了。
但是当我构建它并从库导入时,它不起作用。
我的vite.config.ts如下:
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
"@": path.resolve(__dirname, "src")
}
},
build: {
cssCodeSplit: true,
sourcemap: true,
lib: {
entry: path.resolve(__dirname, "src/index.ts"),
name: "my-project",
fileName: format => `my-project.${format}.js`
},
rollupOptions: {
external: ["vue"],
preserveEntrySignatures: "strict",
output: {
globals: {
vue: "Vue"
}
}
}
}
});
我认为问题出在rootRef的定义上。看来只有绑定位置才能使用。这与在组件中定义它没有什么不同。我需要在多个地方使用它。
奇怪的是,这样一来,Dev环境可以正常工作,但Pro环境却无法使用。是否需要修改vite的构建配置?
我该怎么做?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
问题是您的
App.vue使用自己的composables/useShow副本,而不是来自库的副本。解决方案是从库中导出可组合项,以便您的应用程序可以使用相同的可组合项:
// src/index.ts import { default as useShow } from './composables/useShow'; //... export default { //... useShow };在
App.vue中,使用 lib 的可组合项:import MyProject from "../dist/my-project.es"; const { changeShow } = MyProject.useShow();GitHub PR