使用 Vue.js 构建本地 Web 组件

Web Components / Custom Elements spec 允许您在浏览器中定义自己的自定义元素和附加的逻辑。 它已经到来很长一段时间,但它几乎在这里。 Web Components 的优势在于它们可以在任何框架或库之间互操作,甚至是Vanilla JS。

安装

Vue 定制元素需要(适当命名) vue-custom-element 插件。

通过 Yarn 或 NPM 安装。

1# Yarn
2$ yarn add vue-custom-element -D
3
4# NPM
5$ npm install vue-custom-element --save-dev

此外,除非您仅为 Chrome 构建,否则您可能需要使用 document-register-element 聚合文件。

创建一个 Web 组件

将您的组件写成正常的样子,单个文件组件如果使用构建系统,就可以正常工作。

 1[label ExampleComponent.vue]
 2<template>
 3  <p>Dynamic prop value: {{myProp}}</p>
 4</template>
 5
 6<script>
 7export default {
 8  props: ['myProp']
 9}
10</script>

然后,在Vue中添加Vie-custom-element插件并注册您的组件。

 1[label main.js]
 2import Vue from 'vue';
 3import vueCustomElement from 'vue-custom-element';
 4
 5import ExampleComponent from './ExampleComponent.vue';
 6
 7// Configure Vue to ignore the element name when defined outside of Vue.
 8Vue.config.ignoredElements = [
 9  'example-component'
10];
11
12// Enable the plugin
13Vue.use(vueCustomElement);
14
15// Register your component
16Vue.customElement('example-component', ExampleComponent, {
17  // Additional Options: https://github.com/karol-f/vue-custom-element#options
18});

现在,在构建一个独立的脚本后,您应该能够将该脚本添加到任何网页,并按照预期进行示例组件渲染。

 1[label index.html]
 2<!DOCTYPE html>
 3<html>
 4  <head>
 5    <meta charset="utf-8">
 6    <title>My Example Vue Page</title>
 7    <script src="dist/build.js" async deferred></script>
 8  </head>
 9  <body>
10    <example-component myProp="I can pass props!"></example-component>
11  </body>
12</html>

Props 仍然会反应,但您无法传输除字符串以外的值。

你有它!用Vue制作的定制元素!

Published At
Categories with 技术
Tagged with
comments powered by Disqus