javascript Vue3 onMounted函数在与rollup捆绑的esm包中不起作用

0s0u357o  于 2023-10-14  发布在  Java
关注(0)|答案(2)|浏览(186)

我将一个vue 3组件与rollup捆绑在一起。组件很简单:

// main.vue
<template>
  <div>
    <div @click="clickDiv">{{ 1 }}</div>
    <div ref="divRef"></div>
  </div>
</template>
<script>
import { onMounted, ref, defineComponent } from 'vue'
export default defineComponent({
  name: 'Vue3Component',
  mounted () {
    console.log('component mounted') // it works well
  },
  setup() {
    const divRef = ref()
    const clickDiv = () => {
      console.log('divRef', divRef) // it causes some warnings
    }
    onMounted(() => {
      console.log('component onMounted') // it causes some warnings
    })
    return {
      a: ref(1),
      clickDiv,
      divRef
    }
  },
})
</script>

和输入项:

// index.js
import Vue3Component from './main.vue'
Vue3Component.install = (app) => {
  app.component(Vue3Component.name, Vue3Component)
}

export {
  Vue3Component
}

汇总配置代码:

// rollup.config.js
import resolve from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
import pkg from './package.json'
import external from 'rollup-plugin-peer-deps-external'
import vuePlugin from 'rollup-plugin-vue'

const extensions = ['.vue', '.js']

const globals = {
  vue: 'Vue',
  'highlight.js': 'hljs',
  'marked': 'marked'
}

export default [
  {
    input: 'src/index.js',
    output: [
      {
        name: 'VueNextMEditor',
        file: pkg.main,
        format: 'umd',
        globals
      },
      {
        file: pkg.module,
        format: 'es'
      },
      {
        name: 'VueNextMEditor',
        file: pkg.unpkg,
        format: 'umd',
        plugins: [terser()],
        globals
      }
    ],
    plugins: [
      external(),
      vuePlugin(),
      resolve(),
      commonjs({ extensions })
    ]
  }
]

当我在本地使用vue-socket测试组件时,安装程序中的onMounted不起作用。浏览器会显示这样的错误:

[Vue warn]: onMounted is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement.
[Vue warn]: Missing ref owner context. ref cannot be used on hoisted vnodes. A vnode with ref must be created inside the render function. 
  at <Vue3Component> 
  at <App>

mounted外的设置功能会工作。谁能帮我解决这个问题?Vue3Component

zaqlnxep

zaqlnxep1#

我解决了这个问题。这是因为我安装了vue两次。我用pnpm link解决了它

$ cd vue3-component
$ pnpm install

$ cd example
$ pnpm link ../node_modules/vue
$ pnpm install
$ pnpm serve

真的有用!

6vl6ewon

6vl6ewon2#

是的,当你安装Vue两次时,显然会发生这种情况。
声明一下我犯了和你一样的错误

Missing ref owner context. ref cannot be used on hoisted vnodes. A vnode with ref must be created inside the render function.

但在我的情况下,这是因为我在Vue应用程序中使用了自制的Vue库,并且在库的构建定义(vite.config.js)中,我没有正确放置此选项以避免Vue捆绑在库中:

external: ['vue'],

我把它直接放在build下面,而不是按照Vite文档的规定放在rollupOptions下面:https://vitejs.dev/guide/build.html#library-mode
好难找啊!我希望从Vue得到一个更好的错误消息,因为这是神秘的!

相关问题