函数式组件调用思路
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>