首页 > 解决方案 > 带有 v-model 的与框架无关的自定义元素不起作用

问题描述

我面临一个问题。我目前正在使用新的浏览器 API 开发一个与框架无关的元素库,customElements.define()并创建了一个自定义输入,并希望他使用 v-model 绑定。

但是,它不起作用。我可以绑定一个值,:value="prop"但 v-model 根本不起作用。

class LmTag extends HTMLElement {
  constructor() {
    super();
    this.template = document.querySelector("#lmTag");
    this.shadow = this.createShadowRoot();
    this.clone = document.importNode(this.template.content, true);
    this.shadow.appendChild(this.clone);
    this.input = this.shadow.querySelector('input');
  }
  
  connectedCallback() {
    this.value = this.getAttribute("value");
  }
  
  get value() {
    return this.input.value;
  }
  
  set value(value) {
    this.input.value = value;
  }
  
  attributeChangedCallback(attr, oldValue, newValue) {
    console.log(attr, oldValue, newValue);
  }
}

customElements.define("lm-tag",  LmTag);

Vue.config.productionTip = false
Vue.config.devtools = false;
new Vue({
  el: '#app',
  data: {
    lights: true,
    input: "model"
  },
  methods: {
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template id="lmTag">
  <style>
    .lm-tag {
      display: inline-block;
      padding: 4px;
      border-radius: 4px;
      background-color: #e74c3c;
      color: #ffffff;
      font-size: 12px;
    }

    .lm-tag input {
      border: none;
    }
  </style>
  <span class="lm-tag">
    <input type="text"/>
    <content></content>
  </span>
</template>
<div id="app" class="text-center body">
  <p>
    Binding :value
    <lm-tag :value="input">{{input}}</lm-tag>
  </p>
  <p>
    Binding v-model
    <lm-tag v-model="input">{{input}}</lm-tag>
  </p>
  <p>
    Raw input with :value
    <input type="text" :value="input">
  </p>
  <p>
    Raw input with v-model
    <input type="text" v-model="input">
  </p>
</div>

你能帮助一个在他的代码上有问题的开发人员吗?

谢谢!

标签: vue.js

解决方案


推荐阅读