Typescript+vue cli3组件传参

子传父
父组件:

<template>
      <div>
            <son @add='add'></son>
      </div>
</template>
<script lang='ts'>
    import { Component, Vue } from "vue-property-decorator";
    import son from "../components/son.vue";
    @Component({
          components: {
            son
        }
    })
    export default class Father extends Vue {
       protected data: any = [];
      //子组件传递的参数是个对象所以这边接收也要定义对象接收
       add(obj: any) {
            this.data.push(obj);
            console.log(this.data);
        }
    }
</script>

子组件:

<template>
    <div>
          <button @click="add"></button>
    </div>
</template>

<script lang='ts'>
     import { Component, Vue, Emit } from 'vue-property-decorator';
    //要引入Emit向父组件传参
    @Component({

    })
    export default class Son extends Vue {
        public name: string = "";
        public age: string = "";
        public sex: string = "";
        public height: string = "";
        @Emit("add")  
        send(obj: any) {  // send 处理给父组件传值的逻辑
                //
        } //里面写个(//)注释是因为里面不能为空
        add() {
            this.send({name: this.name, age: this.age, sex: this.sex, height: this.height })
        }
    }
</script>

父传子
父组件:

<template>
      <div>
            <son :flag='flag'></son>
      </div>
</template>
<script lang='ts'>
import { Component, Vue } from "vue-property-decorator";
import list from "../components/list.vue"
@Component({
  components: {
    list
  },
export default class Father extends Vue {
      protected flag:Boolean=false;
}
</script>

子组件:

<template>
      <div>
          <span>{{ flag }}</span>
      </div>
</template>
<script lang='ts'>
import {Component, Prop, Vue} from "vue-property-decorator";
    @Component({

    })

    export default class Son extends Vue {
        // 接受父组件的值 
        @Prop({
            type: boolean, // 父组件传递给子组件的数据类型
            required: false, // 是否必填
            default: ' ' // 默认值, 如果传入的是 Object,则要 default: ()=>({}) 参数为函数
        })  flag!: boolean;

        created() {}
    }
</script>

兄弟组件传参的话就让一个组件传给父组件,父组件再传给另一个子组件,实现起来比较麻烦,或者可以使用vuex将数据存储在公共管理工具中,官网上说有个vuex-class的插件,我也没用过,用的还是es6的扩展运算符的方式对vuex进行传值等操作,效果都是一样的

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值