vue.js - 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)
解决方案
用过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,
}
}
推荐阅读
- apache-zookeeper - Zookeeper 集群有两个节点
- javascript - 进行三重比较时会发生什么?(Javascript)
- ruby-on-rails - Rails:ActiveRecord::RecordNotFound 找不到没有 ID 的照片
- ruby-on-rails - rails 5 algolia search - 按用户状态过滤结果
- java - 我没有收到我传递的第二个活动意图的字符串
- python - 子类化方法在虚拟环境中的站点包中显示错误
- r - 关于 R 中日期时间转换的困惑
- javascript - 在 Javascript 中返回回调
- java - 如何通过 VisualVM 从堆转储中获取对象的地址?
- php - 在 CodeIgniter 中统计一个类别的帖子