vue 中父子组件传值,以及子组件调用父组件方法,父组件调用子组件方法

先创建子组件
创建一个分页的子组件

<template>
  <div>
      <el-pagination
        background
        layout="prev, pager, next"
        :page-size="5"
        :total=totalPage
        @current-change="callParentFunction($event)"
        style="text-align: center;margin-top: 20px;"
        >
      </el-pagination>
  </div>
</template>

<script>
  export default {
    name: 'v-bottomPage',
      // 接受父组件的值,totalPage后台返回数据的总条数,
    props: {
      totalPage: Number,
      required: true
    },
    data() {
      return {
       items:[]
      }
    },
    created() {

   },
    methods:{
      //子组件定义的方法
      query(){
        console.log('子组件中的方法:从父组件接收到的参数:'+this.totalPage);
      },
       // 子组件调用父组件的方法
      callParentFunction(event){
         this.$parent.fatherMethod(event);
      }
    },
}
</script>
<style>
</style>

父组件代码部分


<template>
    <div class="app-container">
	<div>这里是父组件</div>	
	
    <v-BottomPage
    :totalPage="items.length"
    >
    </v-BottomPage>
</div>
</template>

<script>
  import vBottomPage from '../../../components/bottomPage.vue'
  export default {
    components:{
      vBottomPage
    },
    data() {
      return {
        items:[1,2,3,4,5,6,,4,8,,9,6,5],
      };
    },
    created() {

    },
    methods: {
      fatherMethod:function(event){
        console.log('父组件中的方法: 当前点击的页数是'+JSON.stringify(event))
      },
      //父组件调用子组件的方法
      fuzujian(){
        this.$refs.child.query();
      },
      query:function(){
      //模拟请求到数据,
        this.items.concat([1,2,3,4,5]);
      }
    }
  };
</script>
<style>
</style>

子组件通过 props接收父组件传的参数

props: {
	//参数的名称,定义接收类型为数子
      totalPage: Number,
      required: true
    },

父组件传递给子组件totalPage

<v-BottomPage  :totalPage="items.length"  >  </v-BottomPage>

父组件调用子组件的方法

fuzujian(){
   this.$refs.child.query();
}

子组件调用父组件的方法,这里总结了三种
1 常用的方法

 this.$parent.fatherMethod();

2 方法是在子组件里用$emit向父组件触发一个事件,父组件监听这个事件就行了。

 childMethod(){   this.$emit('fatherMethod');  }

3 父组件把方法传入子组件中,在子组件里直接调用这个方法

    props: {
        fatherMethod: {
           type: Function,
           default: null
           } 
        },
       childMethod() {
      	 if (this.fatherMethod) {
         this.fatherMethod();
         }
       }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值