我用VueCli3
创建了一个vuejs web组件,最终编译好的组件是这样的:
<script src="https://unpkg.com/vue"></script>
<script src="./my-lib.js"></script>
<my-lib></my-lib>
此 Web 组件只是创建一个具有某些值的隐藏输入。当我在浏览器中检查它时:
<my-lib>
#shadow-root (open)
<style type="text/css">....</style>
<div data-v-1ca2f958="" id="app">
<input type="hidden" name="my_input" value="some value">
</div>
</my-lib>
我想在非 Vue 页面的 form
中使用它以及其他输入,如下所示:
<form method="post" action="/test.php">
<input type="text" name="title" value="foo">
<my-lib></my-lib>
<button type="submit">submit</button>
</form>
现在的问题是当我提交表单时,后台只出现title
参数,my_input
参数不存在!
我应该怎么做才能让它发挥作用?
最佳答案
When you use web component with shadow DOM, the input elements within shadow DOM are not submitted with traditional form submission. Read here for more details.
一般来说,唯一的选择是引入一些 JavaScript 来提交您的表单。我能想到的最简单的方法是使用 FormData
当触发提交事件时,然后手动内省(introspection)所有自定义元素。
function onSubmit() {
const form = document.querySelector("form");
const formData = new FormData();
for (let x of form.elements) {
formData.append(x.name, x.value);
}
const customField = form.querySelector("my-lib");
// Some way to access the custom form field's value
formData.append("custom-field-name", customField.customValue);
// Submit now
// Write code to submit form using XHR or Fetch API
}
要保存一些击键,您可以避免 for 循环,因为您可以使用现有表单创建 FormData
:
const form = document.querySelector("form");
const formData = new FormData(form);
关于javascript - 如何在非 vue 网络应用程序中使用 Vuejs 网络组件作为输入元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57950340/