文章中归纳了七种不同的非SFC组件,并将它们集中在一个文件中
- src/subs/index.tsx
import {h, type VNode} from 'vue'
//无状态函数组件
export function C1(props:any,context:any) {
function handle(){
context.emit("infoChange","subInfo 1")
}
return h('h1',{onClick:handle},"C1:"+props.info)
}
//无状态函数组件(内部解构出emit)
export function C2(props:any,{emit}:{emit:(eventName:string,payload:string)=>void}){
function handle(){
emit("infoChange","subInfo 2")
}
return <h1 onClick={handle}>C2:{props.info}</h1>
}
//标准option式组件(使用渲染函数)
export const C3={
props:{info:String},
render():VNode{
return h("h1",{onClick:this.handle},"C3"+this.info)
},
methods:{
handle():void{
this.$emit("infoChange","subInfo 3")
}
}
}
//标准option式组件(使用JSX)
export const C4={
props:{info:String},
render(){
return <h1 onClick={this.handle}>C4:{this.info}</h1>
},
methods:{
handle(){
this.$emit("infoChange","subInfo 4")
}
}
}
//标准option式组件(使用template方式)
//注意:vue的引出需要使用如下库:'vue/dist/vue.esm-bundler.js',以支持template方式
export const C5={
props:{info:String},
template: `<h1 @click="handle">C5:{{info}}</h1>`,
methods:{
handle(){
this.$emit("infoChange","subInfo 5")
}
}
}
//composition 方式引出(使用JSX)
export const C6={
props:{info:String},
setup(props:any,context:any){
function handle(){
context.emit("infoChange","subInfo 6")
}
return ()=><h1 onClick={handle}>C6:{props.info}</h1>
}
}
//composition 方式引出(使用函数)
export const C7={
props:{info:String},
setup(props:any,context:any){
function handle(){
context.emit("infoChange","subInfo 7")
}
return ()=>h("h1",{onClick:handle},"C7:"+props.info)
}
}
- 父组件: src/Main.vue
<template>
<button @click="()=>changeHandle(Math.random()+'')">改变信息</button>
<c1 :info="info" @infoChange="changeHandle"></c1>
<c2 :info="info" @infoChange="changeHandle"></c2>
<c3 :info="info" @infoChange="changeHandle"></c3>
<c4 :info="info" @infoChange="changeHandle"></c4>
<c5 :info="info" @infoChange="changeHandle"></c5>
<c6 :info="info" @infoChange="changeHandle"></c6>
<c7 :info="info" @infoChange="changeHandle"></c7>
</template>
<script lang="ts" setup>
import {ref} from 'vue'
import {C1,C2,C3,C4,C5,C6,C7} from './subs'
const info=ref("父组件信息")
function changeHandle(value:string){
info.value=value
}
</script>
<style>
h1{
cursor: pointer;
}
h1:hover{
color: red;
}
</style>
网友评论