
需求分析:
组件解构
- 动词:关闭 => Event.close
- 消息:消息 => Props.msg
- 横幅:类型 => Props.type
定义组件
- 定义props.type参数类型
type messageType = 'message' | 'wraning';
- 定义props.msg参数类型?好吧!其实就是一个
string
- 定义props
const props = {
msg: {
default: "",
type: String
},
type: {
default: "message",
type: String as PropType<messageType>
}
}
- 定义组件样式
- 说明:这里类型算是比较鬼畜的,但是比较优秀的是后期不用为了类型错误发愁
const style: Record<string, Record<string, any>> = {
commStyle: {...
},
message: {...
},
wraning: {...
},
close: {...
}
}
- 定义组件
export default defineComponent({
props: props,
setup(this,props, ctx) {
const { msg } = props;
const message: Ref<string> = ref(msg);
const close = () => {
console.log(ctx);
console.log(this);
ctx.emit("close",ctx)
}
return { message, close };
},
render() {
const currentStyle: Record<string, string> = {
...style.commStyle,
...style[this.type]
}
return (
<div style={currentStyle}>
<span>{this.message}</span>
<span style={style.close} onClick={this.close}>关闭</span>
</div>
)
}
});
- setup的定义
setup?: (this: void, props: Props & UnionToIntersection<ExtractOptionProp<Mixin>>
& UnionToIntersection<ExtractOptionProp<Extends>>,
ctx: SetupContext<E>) => Promise<RawBindings> | RawBindings | RenderFunction | void;
- setup函数
- 这玩意是vue3特有的
- 在setup里面你可以使用下面生命周期钩子函数
Options API | Hook inside setup |
---|
beforeCreate | Not needed* |
created | Not needed* |
beforeMount | onBeforeMount |
mounted | onMounted |
beforeUpdate | onBeforeUpdate |
updated | onUpdated |
beforeUnmount | onBeforeUnmount |
unmounted | onUnmounted |
errorCaptured | onErrorCaptured |
renderTracked | onRenderTracked |
renderTriggered | onRenderTriggered |
- ctx的参数
- 调用
<template>
<div class="home">
<img alt="Vue logo" src="../assets/logo.png" />
<HelloWorld msg="Welcome to Your Vue.js + TypeScript App" />
<TestComm type="wraning" msg="我是一个简单的message" @close="closeEvent" />
</div>
</template>
<script lang="ts">
import { Options, Vue } from "vue-class-component";
import HelloWorld from "@/components/HelloWorld.vue";
import TestComm from "./test";
import { SetupContext } from "vue";
@Options({
components: {
HelloWorld,
TestComm,
},
})
export default class Home extends Vue {
public closeEvent(args: SetupContext) {
console.log(args);
}
}
</script>