绝对不是标题党啊,原理是这样的:
将vue3组件先编译成web components,然后在react项目中使用这个web components就完事了。然后我还还试了一下vue嵌套vue,在一番瞎搞之下,成了。有图有真像。
前置条件
vue 使用3.2 +,因为vue中有一个api叫: defineCustomElement
,可以将vue组件编译成web components
。 好了,文章就写到这儿,你们自己去试吧,差不多得嘞!
使用类tailwind+vue来开发web component
不管是传统vue也好,还是react也好,个人觉得使用tailwind这种“开历史倒车式的行为”是能够极大的提升开发体验和开发速度的,不了解tailwind可以简单的看这里,功能、语法差不多的windicss还支持属性式写法。对比如下:
<button class="bg-blue-400 hover:bg-blue-500 text-sm text-white font-mono font-light py-2 px-4 rounded border-2 border-blue-200 dark:bg-blue-500 dark:hover:bg-blue-600">
Button
</button>
复制代码
属性式写法:
<button
bg="blue-400 hover:blue-500 dark:blue-500 dark:hover:blue-600"
text="sm white"
font="mono light"
p="y-2 x-4"
border="2 rounded blue-200"
>
Button
</button>
复制代码
不用离开html就可以写样式,极大的延长了鼠标滚轮的寿命。然而tailwind和windicss 均不能将css嵌入web componts中,所以可以用老老实实用less/scss吧,本文结束。经过本人的一番调研,发现一位大佬写出了,unocss,支持将css嵌入vue style标签中。然后再配合上vue 3.2中web component的转换规则,将*.vue 转为*.ce.vue。即可将css转为真·内联css,不随转web components而消失。编译之后的效果是这样的:
// 原文件,必以ce结尾!
<script setup lang="ts">
import { ref } from 'vue'
const count = ref(0)
</script>
<template>
<button type="button" @click="count++"
text="sm white"
font="mono light"
p="y-2 x-4"
border="2 rounded blue-200"
>test1命名包含ce,试一试效果 count is: {{ count }}</button>
</template>
复制代码
vue嵌套vue
直接嵌套一定会直接GG,没说的,css变量全消失,本文的例子可以说明这点。
代码如下:
<script setup lang="ts">
import test1Vue from './test1.ce.vue';
</script>
<template>
<div>
直接使用*.vue:
<test1Vue></test1Vue>
</div>
<div>
使用{{ "\<l-compnent-1/\>"}}
<l-compnent-1 />
</div>
</template>
复制代码
如果要1.vue1 写在2.vue中,那么只能写把1.vue 注册成web components。customElements.define('l-compnent-1', 1.vue)
。
适用范围
用一个vue写一个组件库,就可以很方便的用在其它的框架中了啊,什么react,Angular,Svelte都可以,多好啊。