![](http://static.javashuo.com/static/loading.gif)
需求分析:
組件解構
- 動詞:關閉 => Event.close
- 消息:消息 => Props.msg
- 橫幅:類型 => Props.type
定義組件
- 定義props.type參數類型
type messageType = 'message' | 'wraning';複製代碼
- 定義props.msg參數類型?好吧!其實就是一個string
- 定義props
// propsconst props = { msg: {default: "",type: String
}, type: {default: "message",type: String as PropType<messageType>
}
}複製代碼
- 定義組件樣式
- 說明:這裏類型算是比較鬼畜的,可是比較優秀的是後期不用爲了類型錯誤發愁
// 樣式const style: Record<string, Record<string, any>> = { commStyle: {...
}, message: {...
}, wraning: {...
}, close: {...
}
}複製代碼
- 定義組件
// 定義組件
// 這個Vue方法新增了setup,其餘的和之前同樣
export default defineComponent({
props: props,
// setup有三個參數
// void類型的this和props以及ctx
setup(this,props, ctx) {
// 解構props裏面的msg
const { msg } = props;
// 定義一個響應式變量message
const message: Ref<string> = ref(msg);
const close = () => {
// ctx => object
console.log(ctx);
// this => undefined
console.log(this);
// emit
ctx.emit("close",ctx)
}
return { message, close };
},
// render
render() {
// 合併樣式
const currentStyle: Record<string, string> = {
...style.commStyle,
...style[this.type]
}
// jsx
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的參數
// ctx參數// attrs: Proxy// emit: (event, ...args) => instance.emit(event, ...args)// expose: exposed => {…}// props: Proxy// slots: Proxy複製代碼
- 調用
<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"; // @ is an alias to /srcimport 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>複製代碼