How to use render function in <script setup> Vue3

Viewed 5453

I use Vue 3.1.1

I am using script setup in the experimental stage with single file components. Using the script setup, I understand defineProps, defineEmit, and useContext, but I don't understand how to use the render function.

<script lang="ts" setup>
import { defineProps } from 'vue'

const props = defineProps<{
    text: string
}>()

const handleClick = () => {
    console.log('click!!')
}

// Render function...

/* The template I want to create.
    <button
        class="btn btn-primary"
        type="button"
        @click="handleClick"
    >
        {{ props.text }}
    </button>
*/
</script>
3 Answers

try it.

<script lang="tsx" setup>
  import { h } from 'vue';

  const render = () => {
    return h('div', []);
  };

  const jsxNode = () => {
    return <div> text </div>;
  };
</script>
<template>
  <render />
  <jsxNode />
</template>

Try to use the h function to create your element then render it inside the template section as follows :

<script setup lang="ts">
import { ref,h } from 'vue'

const props = defineProps<{
    text: string
}>()

const handleClick = () => {
    console.log('click!!')
}

const root=h('button',
             {type:'button',onClick:handleClick,class:'btn btn-primary'},props.text)

</script>

<template>
  <root/>             
</template>

DEMO

You may try an extra normal script.

<script lang="tsx" setup>
import { defineProps, defineExpose } from 'vue'

const props = defineProps<{
    text: string
}>()

const handleClick = () => {
    console.log('click!!')
}
defineExpose({
  handleClick,
  // other data,method
})
</script>

<script lang="tsx">
import { defineComponent } from 'vue'

export default defineComponent({
  render() {
    return (
      <button
        class="btn btn-primary"
        type="button"
        onClick={this.handleClick}
      >
        {{ this.text }}
      </button>
    )
  }
})
</script>

Any data, methods except the props should be exposed using defineExpose.

BTW, setup script and normal script should have the same lang attribute.

Related