vue3的函数式组件调用 (h+render)

函数式组件调用思路

1.先使用h函数将组件转换为虚拟dom VNode
2.决定将这个虚拟dom 渲染的位置
3.使用render将虚拟dom 渲染到真实dom上

实现

APP.vue
1.不需要像以往一样 注册组件 而只需要调用打开组件的方法
2.思维有点类似 我们使用alert(‘’) 弹出的窗是个组件
3.这样只需要在使用的地方调用打开方法就可以使用组件

<template>
  <div @click="clickFun">点击渲染组件</div>
</template>
<script setup>
import { showFun } from './js/index'//----------******这里*****-------
import { ref } from 'vue'
let name = ref('向组件内传递的参数')
const clickFun = () => {
  showFun(name.value)  //---------********这里**********----------
}
</script>

打开组件的js代码封装

import zujian from '@/components/index.vue'
import { h, render } from 'vue'
// 2.决定将这个虚拟dom 渲染的位置
const addss = document.createElement('div')
//显示组件
function showFun(value) {
    // 1.先使用h函数将组件转换为虚拟dom VNode
    // 第一个参数是你需要转换成虚拟dom的元素
    // 第二个参数可以是组件传递的参数
    const VNode = h(zujian, { value })
    // 2.决定将这个虚拟dom 渲染的位置
    // const addss = document.createElement('div')
    addss.className = 'box'
    document.body.appendChild(addss)
    // 3.使用render将虚拟dom 渲染到真实dom上
    render(VNode,addss)
}
//关闭组件
function noShowFun() { 
    document.body.removeChild(addss)
}
export{showFun,noShowFun}

组件本身 vue文件

<template>
  <div>
    <div @click="clickFun">这是一个组件 这是组件传来的参数:{{ obj.value }}</div>
  </div>
  </template>
  <script setup>
  import { defineProps } from 'vue'
  import { noShowFun } from '../js/index'
  //接受使用组件方传来的参数
  let obj = defineProps(['value'])
  const clickFun = () => {
    //调用关闭组件的方法
    noShowFun()
  }
  </script>
  <style scoped>
  div{
    position: fixed;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    margin: auto;
    width: 500px;
    height: 500px;
    background-color: aquamarine;
    color: black;
  }
  </style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值