Last active
January 7, 2022 10:59
-
-
Save spaceemotion/bf6f2c7dd095bf51c8320778d102feb1 to your computer and use it in GitHub Desktop.
setFormValue for CustomElements in Vue3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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