为了账号安全,请及时绑定邮箱和手机立即绑定

是否可以在传统的html表单中添加vue组件?

是否可以在传统的html表单中添加vue组件?

临摹微笑 2023-09-11 16:03:02
是否可以将vue输入组件添加到标准html表单中?我知道这不是处理 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?
查看完整描述

1 回答

?
holdtom

TA贡献1805条经验 获得超10个赞

<input>提交表单时,浏览器应包含表单中的任何元素。浏览器不会关心它是否<input>位于 Vue 组件内。


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


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


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>


查看完整回答
反对 回复 2023-09-11
  • 1 回答
  • 0 关注
  • 48 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信