DEV Community

Yuqing Ma
Yuqing Ma

Posted on

How to use v-model in render function vue 3 composition API?

Introduction:
This article focus on v-model in render function with two kinds of components, custom components and pre-built components. From the official document on VueJs, v-model directive is expanded to modelValue and onUpdate:modelValue props during template compilation—we will have to provide these props ourselves:

export default {
props: ['modelValue'],
emits: ['update:modelValue'],
render() {
return h(SomeComponent, {
modelValue: this.modelValue,
'onUpdate:modelValue': (value) => this.$emit('update:modelValue', value)
})
}
}

Soon, you will be confused about where to use the emits and props. In most cases, emits and props are defined in child components and render functions are used in parent components.
Render function applications in custom components:
Let’s define the child component first.
Child Component
`

  • {{ tag }}


<br> const props = defineProps({<br> title: String<br> })<br>
We need a props from parent components to pass data to child components. So, title is the props in the child component. The we need to pass data to title in render function from parent component.
<br> render(){<br> return h(<br> Childcustomcom,<br> {<br> ‘title’:[‘hello’,’this’,’is’,’array’],<br> }<br> )<br> }</p> <p><script lang="ts"><br> import Childcustomcom from &#39;./childcustomcom.vue&#39;</p> <p>export default{<br> name: &#39;customcom&#39;,<br> components: {<br> Childcustomcom<br> }<br> }<br> `

Now we are done with props. Then we need to pass data from the child component to parent component. We need an emits.
child Component
`

  • {{ tag }}


<br> const props = defineProps({<br> title: String<br> })<br> const newTag = ref(&#39;&#39;)<br> const emit = defineEmits([&#39;addTag&#39;])<br> function handleinput(){<br> emit(‘addTag, newTag.value)<br> }</p> <p>
In side render function we need v-on to trigger the event. V-on in render function is on the capitalized
render(){
return h(
Childcustomcom,
{
‘title’:[‘hello’,’this’,’is’,’array’],
‘onAddTag’ : (value) ={
console.log(value)
},
},
)
}`
Render function applications in pre-built components:
We use the example from the Naive UI components. https://www.naiveui.com/en-US/os-theme/components/dynamic-input
Ninput has dynamic props including v-model value (Value in controlled mode)
but we cannot the value props directly, it will cause error.
Inside render function:

`render(){
return h(
NInput,
{

'default-value': customvalue,
'on-change': (v:string)=>{
customvalue=v
},
type:"text",
})}
},

const customvalue = ref(‘’)

`Here we need on-change call back function to update the value from input to customvalue, the default-value props to give the initial value to ninput.

Top comments (0)