vue-property-decorator和typescript结合构建的class类组件,父组件触发子组件方法的方式

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; // 非必传
    
        @Ref() private readonly son!: Son
    
        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 Son).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 Son).handleChangeDesc('你好,中国')
      }
      
    • <数据类型> ===>> 比如

      handleSonMethod() {
           // 调用子组件的handleChangeDesc方法
           (<Son>this.$refs.son).handleChangeDesc('你好,中国')
      }
      
  • 第二种方式:Ref

    // 1. 在定义Ref时指定数据类型为Son
    @Ref() private readonly son!: Son
    
    // 2. 使用的时候就可以直接this.son
     this.son.handleChangeDesc('你好,中国')
    
  • 效果图

    • 触发前

    • 触发后

posted @ 2019-07-22 17:47  _Jarrett  阅读(2839)  评论(3编辑  收藏  举报