Vue学习14----父组件给子组件传值

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhaihaohao1/article/details/89021527

父组件给子组件传值
可以传数据
可以传方法
可以传父对象

1.父组件调用子组件的时候 绑定动态属性

 <IHome :title="title"></IHome>

2、在子组件里面通过 props接收父组件传过来的数据

 props:['title'],

3、在子组件中,展示父组件传过来的值

 <div>{{title}}</div>

下面写个例子:
效果图:
在这里插入图片描述
项目结构:
在这里插入图片描述

App.vue是父组件
Home.vue是子组件
代码:
App.vue

<!--父组件给子组件传值-->
<template>
  <div>
    <!--通过属性给子组件传值-->
    <!--title 传值-->
    <!--iFatherMethod 传方法-->
    <!--:iapp="this" 传对象-->
    <IHome :title="title" :iFatherMethod="iFatherMethod" :iapp="this"></IHome>
    <div class="content">内容</div>
  </div>
</template>

<script>
  /**
   父组件给子组件传值
   可以传数据
   可以传方法
   可以传父对象

   1.父组件调用子组件的时候 绑定动态属性
   <IHome :title="title"></IHome>
   2、在子组件里面通过 props接收父组件传过来的数据
   props:['title'],
   3、在子组件中,展示父组件传过来的值
   <div>{{title}}</div>

   */
  import IHome from './components/Home.vue';

  export default {
    name: 'app',
    data() {
      return {
        title: '标题',
        content:'内容',
      }
    },
    methods:{
      iFatherMethod(arge){
        alert('父组件的iFatherMethod'+arge);
      }
    },
    components: {
      /*前面的组件名称不能和html标签一样,会出现冲突*/
      'IHome': IHome,
    }
  }
</script>

<style lang="scss" scoped>
  .content {
    font-size: 50px;
  }


</style>

Home.vue

<!--模板,里面写html-->
<template>
  <!--根组件,只能有一个根组件-->
  <div>
    <!--显示父组件传过来的值-->
    <div class="head">{{title}}</div>
    <button @click="iFatherMethod(123)">接收父组件传过来的方法</button>
    <button @click="igetFather">获取父组件的对象</button>

  </div>
</template>

<!--script里面写逻辑-->
<script>
  export default {
    name: "IHeader",
    data() {
      return {
        msg: '头部组件',
      }
    },
    methods: {
      igetFather() {
        //调用父类的数据
        alert(this.iapp.title);
        //调用父类的方法
        this.iapp.iFatherMethod(123);
      }
    },
    //子组件中,接收到父组件传过来的值
    props: ['title', 'iFatherMethod', 'iapp'],

  }
</script>


<!--style里面写样式-->
<style lang="scss" scoped>
  /*scoped  css只在本文件中起作用*/
  .head {
    width: 100%;
    line-height: 150px;
    text-align: center;
    background-color: aqua;
    font-size: 50px;
  }

  button {
    width: 100%;
    line-height: 150px;
    text-align: center;
    font-size: 50px;
  }

</style>

源码下载:

猜你喜欢

转载自blog.csdn.net/zhaihaohao1/article/details/89021527