vue-property-decorator和typescript結合構建的class類組件,父組件觸發子組件方法的方式
class類組件示例
-
Father類組件
<template> <div> <h1>父組件</h1> <button @click="handleSonMethod">點擊觸發子組件方法(修改子組件的描述)</button> <Son ref="son" /> </div> </template> <script lang='ts'> // lang要定義為ts import { Vue, Prop, Component } from "vue-property-decorator"; import Son from "./Son.vue"; @Component({ name: "Father", components: { Son } }) export default class Father extends Vue { // prop @Prop(Array) sub_projects!: string[]; // 必傳 @Prop(String) selected_project?: string; // 非必傳 // data son: any = null // 存儲子組件 selected_org: string = "1"; options: Array<{ value: string; label: string }> = [ { value: "1", label: "1" }, { value: "2", label: "2" }, { value: "3", label: "3" } ]; // computed 計算屬性 get username(): string { return `計算屬性username`; } // 鈎子函數 created() { console.log("created鈎子觸發了"); } // method 方法 handleSonMethod() { // 調用子組件的handleChangeDesc方法 (this.$refs.son as any).handleChangeDesc('你好,中國') } } </script>
-
Son類組件
<template> <div> <h2>子組件的描述信息:<span style='color: red'>{{ desc }}</span></h2> </div> </template> <script lang='ts'> import { Vue, Component } from "vue-property-decorator"; @Component({ name: "Son" }) export default class Son extends Vue { // data desc: string = "我是子組件Son"; /** * @description: 修改子組件展示的描述信息 * @param { string } msg 子組件描述信息 */ handleChangeDesc(msg: string) { this.desc = msg; } } </script>
父組件觸發子組件方法的方式
-
以前的方式
this.$refs.son.handleChangeDesc('你好,中國')
- 會報錯,因為引入了typescript
-
第一種方式:類型斷言
-
as 關鍵字(推薦用這種)
handleSonMethod() { // 調用子組件的handleChangeDesc方法 (this.$refs.son as any).handleChangeDesc('你好,中國') }
-
<數據類型> ===>> 比如
handleSonMethod() { // 調用子組件的handleChangeDesc方法 (<any>this.$refs.son).handleChangeDesc('你好,中國') }
-
-
第二種方式:將this.$refs.son賦值給一個組件的一個屬性
// 1. 組件上定義一個可以存儲任意數據類型值的屬性‘son’ son: any = null // 存儲子組件 // 2. 將子組件的實例賦值給‘son’,通過這個變量去調用子組件的方法 handleSonMethod() { // 調用子組件的handleChangeDesc方法 this.son = this.$refs.son this.son.handleChangeDesc('你好,中國') }
-
效果圖
-
觸發前
-
觸發后
-