vue组件之间的传值-父与子的传值 子组件传值父组件 兄弟组件之间的传值。

子组件和父组件的传值  

 父组件:

<template>
  <!-- html界面 必须有主DIV包裹 -->
  <div>
    <h1>我是父组件----子组件在下面</h1>
    <v-son title="我是父组件" message="交给你一项任务"></v-son>
  </div>
</template>

<script>
  //导入子组件
  import son from "./01-son.vue";
  export default {
    data() {
      return {
        msg: ""
      };
    },
    components: {
      "v-son": son
    }
  };
</script>

<style lang="less" scoped>
</style>

在 父组件中引用子组件 01-son.vue ,然后在父组件中注册一下     在v-son 子组件中 添加任意的 title message 

 

子组件 :

<template>
  <!-- html界面 必须有主DIV包裹 -->
  <div>
    <h1>{{msg}}</h1>
    <h1>父组件传过来的值 title-{{title}} 与 message {{message}}</h1>
  </div>
</template>

<script>
  //导入子组件
  //   import son from "./01-son.vue";
  export default {
    props: ["title", "message"],
    data() {
      return {
        msg: "我是子组件"
      };
    }
  };
</script>

<style lang="less" scoped>
</style>


在 子组件中通过 props 来获取父组件中传过来的自定义属性title 和message的值并显示在子组件中。

 

 

子组件传值给父组件

 

<template>
  <!-- html界面 必须有主DIV包裹 -->
  <div>
    <h1>{{msg}}</h1>
    <h1>父组件传过来的值 title-{{title}} 与 message {{message}}</h1>

    <button @click="sendMsgToParent">发送消息到父组件</button>
  </div>
</template>

<script>
  //导入子组件
  //   import son from "./01-son.vue";
  export default {
    props: ["title", "message"],
    data() {
      return {
        msg: "我是子组件"
      };
    },
    methods: {
      sendMsgToParent() {
        //使用$emit发送消息
        this.$emit("getMsgFromSub", this.msg);
      }
    }
  };
</script>

<style lang="less" scoped>
</style>


 子组件发送给父组件必须通过事件来发送   this.$emit("getMsgFromSub", this.msg);    getMsgFromSub 是事件的类型 这个随便定义 就是后面的跟父组件对应上就可以了  

 

父组件

<template>
  <!-- html界面 必须有主DIV包裹 -->
  <div>
    <h1>我是父组件----子组件在下面</h1>

    <h2>我是子组件发送过来的消息{{msg}}</h2>
    <v-son title="我是父组件" message="交给你一项任务" @getMsgFromSub="getMsg"></v-son>
  </div>
</template>

<script>
  //导入子组件
  import son from "./01-son.vue";
  export default {
    data() {
      return {
        msg: ""
      };
    },
    components: {
      "v-son": son
    },
    methods: {
      getMsg(msg) {
        this.msg = msg;
      }
    }
  };
</script>

<style lang="less" scoped>
</style>


在父组件中子组件的位置上 声明getMsgFromSub=方法  

在方法内部就可以拿得到子组件传过来的值了。

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值