vue3 + ts 组件库2

588 阅读1分钟

组件库嵌套组件引用的vue不一致问题记录

在前面的文章 《vue3 + ts 组件库》中有写到组件库中vue的依赖要使用peerDependencis。最近在写嵌套组件时,又遇到新的问题,以此记录

  • 嵌套组件:组件库中的一个组件中调用了组件库的另一个组件(自己的定义)
  1. FwInput组件
  • 该文件是一个简单的输入框组件
<template>
    <div><input :placeholder="placeholder" type="text"  /></div>
</template>


<script lang="ts">
import { defineComponent} from 'vue'

export default defineComponent({
    name: 'FwInput',
    componentName: 'FwInput',
    props: {
        placeholder: {
            type: String,
            default:'请填写'
        }
    },
    mounted(){
        console.log("组件fw-input")
    }
})
</script>
  1. FwForm组件
  • 该组件通过传入的标题和组件类型,实现一个带标题的组件
<template>
  <div class="row">
      <div class="title">{{ title }}</div>
       <component :is="currentTabComponent" class="tab"></component>
  </div>
</template>

<script lang="ts">

import fwInput from '../FwInput/index.vue'
import { defineComponent } from 'vue'


export default defineComponent({
    name: 'FwFrom',
    componentName: 'FwFrom',
    props: {
        title: {
            type:String,
            default:'标题'
        },
        type:{
            type:String,
            default:'input'
        }
    },
    computed: {
        currentTabComponent() {
            return 'fw-' + this.type.toLowerCase()
        }
    },
    components :{
        'fw-input': fwInput
    },
    mounted(){
        console.log("组件fw-form")
    }
})
</script>

<style >
.row{
    display: flex;
    justify-content: space-between;
}
</style>
  1. 测试中出现的问题:使用FwForm时输入框没有渲染出来 为了使用方便,我在业务项目中是通过本地引用该组件实现的; 即webpack配置中配置resolve.alias
'vue3-ts-flow-components': 'D://code/vue3-component',
  • 组件项目目录: D://code/vue3-component

  • 业务项目目录: D://code/erp

  • 这样配置导致执行FwForm组件的render函数时,调用的vue是组件项目node_modules文件夹下的vue;正确应该从头至尾只调用业务项目node_modules文件夹下的vue。

  • 最终删除resolve.alias下的vue3-ts-flow-components配置,改为npm install vue3-ts-flow-components ,最终渲染正确。

如何快速的测试自己写的组件呢, 我想还是在组件项目中写测试代码吧! 或者读者们有其他更好的办法?

  1. 最终渲染出来的结果如下:

image.png