Ehan Van的博客
首页
前端笔记
首页
前端笔记
  • 前端笔记

    • v-on的使用
    • 编写一个Vue递归组件
    • 非vue文件中申明的ref如何使用
    • Vue3如何在hook中执行异步函数并同步返回响应式数据
    • 如何终止forEach循环
    • 递归创建下拉树数据
    • 编写一个Vue Web Components
    • js数组toString的使用
    • vueconfig配置多page遇到的坑
    • js事件循环机制
    • React列表渲染中图片闪烁问题
    • 开发中未配置Referrer遇到的坑
    • 前端实现文件分片上传
    • 防抖函数
    • 编写一个vue插件
    • 发布订阅模式

什么是Web Components

兼容性提示 Web Components 模式不支持 IE11 及更低版本。更多细节

注意对 Vue 的依赖 在 Web Components 模式中,Vue 是外置的。这意味着包中不会有 Vue,即便你在代码中导入了 Vue。这里的包会假设在页面中已经有一个可用的全局变量 Vue。

使用vue-cli构建异步Web components

vue-cli-service build --target wc-async --name foo 'src/components/*.vue'

对package.json中的script进行改造,添加一个build:test命令

  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "build:test": "vue-cli-service build --target wc-async --name hello-World src/components/HelloWorld.vue"
  },

运行脚本

npm run build:test

运行后,将在dist目录下将会生成hello-World相关代码

引用Web components

将生成的hello-World.js放到http服务目录下

使用script标签加载

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <div v-if="componentName">
      <component :is="componentName" msg="这是一个异步组件3" />
    </div>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      componentName: "",
    }
  },
  created() {
    this.initComponents()
  },
  methods: {
    initComponents() {
      if (!customElements.get('hello-world')) {
        const script = document.createElement("script");
        script.setAttribute("src", "http://localhost:3333/component");
        document.body.appendChild(script);
      }

      window.customElements.whenDefined("hello-world").then(res => {
        this.componentName = 'hello-world'
      })
    }
  }
}
</script>
Prev
递归创建下拉树数据
Next
js数组toString的使用