search

Home  >  Q&A  >  body text

Vite 2 production environment reference elements are not defined using the compostion api

I'm using vue3 with composition API, but when I build the project, the ref element is always undefined.

I copied it, maybe I used it wrong, but I don’t know why.

  1. I defined a ref in the hooks function.
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. Use rootRef in HelloWorld.vue and link elements.
<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. Create a button in App.vue and bind the click function.
<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>

When I click the button, it works.

But when I build it and import from library, it doesn't work.

My vite.config.ts is as follows:

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"
        }
      }
    }
  }
});

I think the problem lies in the definition of rootRef. It seems that only binding positions can be used. This is no different than defining it in a component. I need to use it in multiple places.

The strange thing is that with this, the Dev environment works fine, but the Pro environment does not. Do I need to modify the build configuration of vite?

what should I do?

P粉714844743P粉714844743285 days ago338

reply all(1)I'll reply

  • P粉041856955

    P粉0418569552024-02-22 09:36:22

    The problem is that your App.vue uses its own copy of composables/useShow instead of the one from the library.

    The solution is to export the composables from the library so that your application can use the same composables:

    // src/index.ts
    import { default as useShow } from './composables/useShow';
    
    //...
    
    export default {
      //...
      useShow
    };
    

    In App.vue, use lib’s composable items:

    import MyProject from "../dist/my-project.es";
    
    const { changeShow } = MyProject.useShow();
    

    GitHub PR

    reply
    0
  • Cancelreply