How to use Web Components in React or Vue All In One
How to use Web Components in React or Vue All In One
Web Components 为可复用组件提供了强大的封装
https://developer.mozilla.org/en-US/docs/Web/Web_Components
React
class HelloMessage extends React.Component {
render() {
return <div>Hello <x-search>{this.props.name}</x-search>!</div>;
}
}
function BrickFlipbox() {
// ✅ class
return (
<brick-flipbox class="demo">
<div>front</div>
<div>back</div>
</brick-flipbox>
);
}
class XSearch extends HTMLElement {
connectedCallback() {
const mountPoint = document.createElement('span');
this.attachShadow({ mode: 'open' }).appendChild(mountPoint);
const name = this.getAttribute('name');
const url = 'https://www.google.com/search?q=' + encodeURIComponent(name);
const root = ReactDOM.createRoot(mountPoint);
root.render(<a href={url}>{name}</a>);
}
}
customElements.define('x-search', XSearch);
https://zh-hans.reactjs.org/docs/web-components.html
Vue
跳过自定义元素
组件的解析
// 仅当使用浏览器内编译时有效
// 如果你正在使用构建工具,请查看下方的配置示例
app.config.compilerOptions.isCustomElement = tag => tag.includes('-')
// vite.config.js
import vue from '@vitejs/plugin-vue'
export default {
plugins: [
vue({
template: {
compilerOptions: {
// 将所有包含短横线的标签作为自定义元素处理
isCustomElement: tag => tag.includes('-')
}
}
})
]
}
// vue.config.js
module.exports = {
chainWebpack: config => {
config.module
.rule('vue')
.use('vue-loader')
.tap(options => ({
...options,
compilerOptions: {
// 将所有以 ion- 开头的标签作为自定义元素处理
isCustomElement: tag => tag.startsWith('ion-')
}
}))
}
}
https://v3.cn.vuejs.org/guide/web-components.html
https://vuejs.org/guide/extras/web-components.html
https://staging-cn.vuejs.org/guide/extras/web-components.html
https://github.com/vuejs/petite-vue
test
Custom Elements Everywhere 测试
⭐️⭐️⭐️
Version: 18.2.0
Browser: Chrome Headless 103.0.5060.114 (Linux x86_64)
Timestamp: 7/21/2022, 9:07:53 PM
15 tests / 0 errors / 7 failures / 0 skipped / runtime: 0.082s
https://custom-elements-everywhere.com/libraries/react/results/results.html
⭐️⭐️⭐️⭐️
Browser: Chrome Headless 103.0.5060.114 (Linux x86_64)
Timestamp: 7/21/2022, 8:42:47 PM
15 tests / 0 errors / 3 failures / 0 skipped / runtime: 0.329s
https://custom-elements-everywhere.com/libraries/vue/results/results.html
Web Components
UI Library
https://github.com/xgqfrms/wcui
https://github.com/XboxYan/xy-ui
refs
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/16522064.html
未经授权禁止转载,违者必究!