除非您需要特定的东西,否则您不需要自己在 Vue 中实现双向数据绑定(太棒了,对吧?)。只需使用
v-model
指令,这是 doc
代码示例:
<vue-input-text v-model="myValue" id="prova_di_un_input_text" name="prova_di_un_input_text" />
const myValue = ref('')
你应该听
事件而不是update:modelValue
。update:value
vue 组件 MyInput.ce.vue
<script setup>
defineProps({
modelValue: String,
})
const emit = defineEmits(['update:modelValue'])
function onInput(event) {
console.log(event.target.value)
emit('update:modelValue', event.target.value)
}
</script>
<template>
<input :value="modelValue" @input="onInput" />
</template>
在main.js中注册Web组件
import { defineCustomElement } from 'vue'
import MyInput from './components/MyInput.ce.vue'
const MyInputEle = defineCustomElement(MyInput)
customElements.define('my-input', MyInputEle)
在 html 中使用
my-input
标签
<my-input value="hello"></my-input>
<br />
<p class="my-p"></p>
<script type="module" src="/src/main.js"></script>
<script>
const myInput = document.querySelector('my-input')
// listen update:modelValue
myInput.addEventListener('update:modelValue', (event) => {
const inputText = event.detail[0]
document.querySelector('.my-p').innerText = inputText
})
</script>