【问题标题】:Is it possible to add a vue component to a traditional html form?是否可以在传统的 html 表单中添加 vue 组件?
【发布时间】:2020-06-26 16:27:55
【问题描述】:

是否可以在标准 html 表单中添加 vue 输入组件?我知道这不是处理 vue 表单的理想方式,但我很好奇将自定义元素添加到现有 html 表单中的“快速而肮脏”的方式的可能性。这是一个假设的例子:

<form action="/users" accept-charset="UTF-8" method="post">
  <input type="email" name="user[email]" />
  <input type="password" name="user[password]" />
  <my-custom-fancy-vue-component />
  <input type="submit"value="Sign up">
</form>

我想知道浏览器是否可以读取 vue 组件中输入元素公开的值,并在用户提交表单时将其作为参数发送。是否有任何其他方法可以告诉浏览器如何从 vue 组件访问值,例如它不使用内部原生输入,可能使用 web 组件作为包装器或使用 shadow dom?

【问题讨论】:

    标签: javascript html vue.js dom


    【解决方案1】:

    提交表单时,浏览器应包含表单中的任何&lt;input&gt; 元素。浏览器不会关心 &lt;input&gt; 是否在 Vue 组件中。

    对于还没有 &lt;input&gt;(或其他合适的表单元素)的组件,您可以添加隐藏输入 &lt;input type="hidden"&gt; 来保存值。

    如果您要包含的组件是第三方组件,那么您将无法直接添加隐藏输入。但是,您仍然可以使用包装器组件来添加它。下面的示例说明了如何处理这种情况。

    const thirdPartyComponent = {
      template: `
        <button
          @click="onClick"
          type="button"
        >
          Increment {{ value }}
        </button>
      `,
      
      props: ['value'],
      
      methods: {
        onClick () {
          this.$emit('input', this.value + 1)
        }
      }
    }
    
    const myCustomFancyVueComponent = {
      template: `
        <div>
          <third-party-component v-model="counter" />
          <input type="hidden" :value="counter">
        </div>
      `,
      
      components: {
        thirdPartyComponent
      },
      
      data () {
        return {
          counter: 4
        }
      }
    }
    
    new Vue({
      el: 'form',
      
      components: {
        myCustomFancyVueComponent
      }
    })
    <script src="https://unpkg.com/vue@2.6.11/dist/vue.js"></script>
    
    <form action="/users" accept-charset="UTF-8" method="post">
      <input type="email" name="user[email]">
      <input type="password" name="user[password]">
      <my-custom-fancy-vue-component></my-custom-fancy-vue-component>
      <input type="submit" value="Sign up">
    </form>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-23
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-01
      相关资源
      最近更新 更多