how to type a formkit node reference in vuejs 3 composition api in typescript

Here's an example of how to create a formkit node reference in Vue.js 3 composition API with TypeScript:

index.ts
import { defineComponent, ref } from 'vue'
import { NodeReference } from '@dansmaculotte/formkit'

export default defineComponent({
  setup() {
    // Create a ref for our node reference
    const nodeRef = ref<NodeReference | null>(null)

    // Pass the nodeRef as a prop to our custom component
    return { nodeRef }
  },
  components: {
    CustomComponent: {
      props: ['nodeRef'],
      setup(props) {
        // Access our node reference through props and use it in our component
        const onInput = (event: any) => {
          if (props.nodeRef) {
            props.nodeRef.setValue(event.target.value)
          }
        }

        // Return any other necessary variables, methods, etc.
        return { onInput }
      },
      template: `
        <input type="text" v-on:input="onInput" />
      `
    }
  },
  template: `
    <div>
      <CustomComponent v-bind:nodeRef="nodeRef" />
    </div>
  `
})
922 chars
37 lines

In this example, we first import the NodeReference class from @dansmaculotte/formkit. We then create a ref using the ref() function and initialize it to null. We pass this ref as a prop to our custom component and access it in the component using props.nodeRef. We can then use the setValue() method on our nodeRef to set its value whenever we need to.

Note that this is just a basic example and the implementation details may vary depending on your specific use case.

related categories

gistlibby LogSnag