Skip to content

Instantly share code, notes, and snippets.

@spaceemotion
Last active January 7, 2022 10:59
Show Gist options
  • Save spaceemotion/bf6f2c7dd095bf51c8320778d102feb1 to your computer and use it in GitHub Desktop.
Save spaceemotion/bf6f2c7dd095bf51c8320778d102feb1 to your computer and use it in GitHub Desktop.
setFormValue for CustomElements in Vue3
import { createApp, defineCustomElement } from 'vue'
import TestComponent from './components/Test.ce.vue';
import App from './App.vue'
const defineCustomFormElement = (el: any) => {
const customElement = defineCustomElement(el);
// @ts-ignore
customElement.formAssociated = true;
return customElement;
}
customElements.define('custom-test', defineCustomFormElement(TestComponent))
createApp(App).mount('#app')
<template>
<input type="text" v-model="query" />
</template>
<script lang="ts">
import { defineComponent, onMounted, watch, computed, getCurrentInstance, ref } from 'vue'
const useInternals = () => {
const internals = ref<any>();
onMounted(() => {
const el = getCurrentInstance()?.root.vnode.el;
if (el !== null && el !== undefined) {
const host = el.parentNode.host;
internals.value = host.attachInternals();
}
})
return internals;
}
const useFormValue = () => {
const internals = useInternals();
return computed({
get: () => {
throw new Error('Only use set');
},
set: (val: any) => {
internals.value?.setFormValue(val);
},
});
}
export default defineComponent({
props: { name: String},
setup() {
const query = ref('');
const formValue = useFormValue();
watch(query, (value) => {
formValue.value = value;
});
return {
query
};
},
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment