vue3中再<script setup>标签下使用渲染函数render方法

2023-10-23 15:33:40

有时候未了方便操作组件,我们需要时用渲染函数来编写组件,再vue3可以再setup函数中返回内容来编写组件,但有时候我们直接使用了<script setup>标签应该如何写呢

第一种方式就是普通的渲染函数来编写 (推荐)

<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>

其实把root函数写成render函数更直观


第二种方式是在tsx模式下,这个模式需要另外配置vue工程,不推荐使用

<script lang="tsx" setup>   import { h } from 'vue';   const render = () => {     return h('div', []);   };   const jsxNode = () => {     return <div> text </div>;   }; </script> <template>   <render />   <jsxNode /> </template>

在渲染函数模式下,我们就可以更改父组件传过来的slots内容了,以达到先修改后生效的效果。

下面以修改slots中的class为例


slots = ()
animationClass = =()=> {
  slotValue = slots.?.()
  (slotValue) {
    ([] && [].&& []..class){
      []..class =[]..class .(animationClass)[]..class =[]..class + +animationClass}
  }
  slotValue[]}


  • 2020-04-01 10:21:20

    Vue extend $mount 构造器详解

    本节介绍两个 Vue.js 内置但却不常用的 API——extend 和 $mount,它们经常一起使用。不常用,是因为在业务开发中,基本没有它们的用武之地,但在独立组件开发时,在一些特定的场景它们是至关重要的。

  • 2020-04-01 15:36:52

    CSS3中的transition属性详解

    transition: property duration timing-function delay transition属性是个复合属性,她包括以下几个子属性: transition-property :规定设置过渡效果的css属性名称 transition-duration :规定完成过渡效果需要多少秒或毫秒 transition-timing-function :指定过渡函数,规定速度效果的速度曲线 transition-delay :指定开始出现的延迟时间

  • 2020-04-02 17:02:25

    vue怎么能像jquery那样获得数据

    有时候我们需要获得动态的元素,但是我们没法直接用vue语法,vue一共了当前组件的对象,我们可以避免使用document.get...之类的。