vite 2 生产环境引用元素未使用 compostion api 定义
P粉714844743
P粉714844743 2024-02-21 14:04:27
0
1
307

我使用带有组合 API 的 vue3,但是当我构建项目时,ref 元素始终未定义。

我复制了一下,可能是我用错了,但不知道为什么。

  1. 我在 hooks 函数中定义了一个 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 };
}
  1. 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>
  1. 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的构建配置?

我该怎么做?

P粉714844743
P粉714844743

全部回复(1)
P粉041856955

问题是您的 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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!