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('你好,中国') }
效果图
触发前
触发后