添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account
import Vue from 'vue'
import wrap from '@vue/web-component-wrapper';
import myPicker from './picker.vue'
const CustomElement = wrap(Vue, myPicker)
window.customElements.define('mypicker', CustomElement)   //这个报错
window.customElements.define('my-picker', CustomElement)

Uncaught DOMException: Failed to execute 'define' on 'CustomElementRegistry': "mypicker" is not a valid custom element name

这是不是就意味着
1 组件名必须得是 中划线化的,不是中划线根本无法注册为web-component了。
2 如果通过customElements.define('my-picker', CustomElement)注册了组件,父组件就不能同时通过

components:{
    'my-picker':myPicker

完整代码如下(vue2 cli直接生成的项目)

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <div @click="handleClick(item.method)">handleCLick</div>
    <div v-for="(item, index) in array" :key="index">
      <div><span @click="handleClick(item.method,item.name)">array-click</span></div>
    </div>
    <my-picker ></my-picker>
  </div>
</template>
<script>
import Vue from 'vue'
import wrap from '@vue/web-component-wrapper';
import myPicker from './picker.vue'
const CustomElement = wrap(Vue, myPicker)
window.customElements.define('my-picker', CustomElement)
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
      item:{
        method:'this is method',
       array:[
        method:'this is array method',
        name:'array item'
  methods:{
    handleClick(args){
      console.log('args',args)
  components:{
    'my-picker':myPicker
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.parentPicker{
  width:100px;
  background-color:green;
  height:100px;
  display:block;
h1, h2 {
  font-weight: normal;
  list-style-type: none;
  padding: 0;
  display: inline-block;
  margin: 0 10px;
  color: #42b983;
</style>
  • Web Component 名称必须含 -,这是标准规定的,跟 Vue 无关。MDN 文档的英文版是有这个说明的 https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry/define#Parameters 标准原文在 https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name
  • 如果看过 Vue 的源码就能知道,Vue 在解析一个标签时,会优先从组件自身的作用域里找是否已经有注册该名字的 Vue 组件,没有的话再当作 Custom Element 处理,所以这对实际使用并没有影响 https://github.com/vuejs/vue/blob/8082d2f910d963f14c151fb445e0fcc5c975cca9/src/core/vdom/create-element.js#L105
  •