首页 > 解决方案 > vue 将共享计算函数编译到单独的包中

问题描述

我如何vue/nuxt在不同的包之间共享通用的特定代码?

我不想使用,monorepo但是我有共享代码,我想将其分离到自己的包中。共享代码(新包)是使用编写的@nuxtjs/composition-api,并且只是在不同的组件/模板中一遍又一遍地共享computed和使用。methods

我不希望将包设置为插件。取而代之的是直接导入以利用摇树的东西(就像composition-api)。

我熟悉rollupjs创建可导入模块。

//New package
//index.js
export { default as isTrue } from './src/isTrue'
...

//src/isTrue
import { computed } from '@nuxtjs/composition-api'

export default (p) => {
  return computed(() => p === 'true') //Im not 100% is this will break reactivity?!?!
}

我没有任何问题.ssr, .esm, .min通过以下方式将其编译成格式rollupjs

我遇到的问题是当我将新包导入工作文件时。

import { isTrue } from 'new-package'

export default{
name: 'testComp',
setup(props){
  return {
    isActive: isTrue(props.active)
  }
}

将产生:

[vue-composition-api] must call Vue.use(VueCompositionAPI) before using any function.

我知道这@nuxtjs/composition-api是 VueCompositionAPI 的包装器。

我真的不想将新包安装为插件,因此我省略了新包上的安装(安装前:https ://github.com/wuruoyun/vue-component-lib-starter/blob/master/src/安装.js

标签: vue.jswebpackvuejs2nuxt.js

解决方案


用过options API

//library.js
export default function(){ // access to this -> arrow function doesnt have this
   return this.disabled == true // when applied using the options api this will be the vue context aka property disabled
}

library.js 使用编译rollupjs并可以导入

//component.vue
import { isDisabled } from 'library'

export default {
  //Composition API:
  setup(props){
   return {
    //stuff
   }
  },
  //Options API:
  computed:{
    isDisabled,
  }
}

推荐阅读