vue父子组件通信(父组件向子组件传递参数,子组件监听参数变化调用对应方法)

1. 父组件

在父组件进行子组件的调用,实现点击按钮的时候再触发子组件的方法调用(点击按钮只是一个举例,只是为了举例说明在特定情况下去触发子组件调用的方法),并且实现父组件向子组件传递参数。

<template>
	<div>
		<div>
			<el-button size="medium" type="primary" @click.native="loadHistoryList">加载历史记录列表</el-button>
		</div>
		<history-list :id="id" :load="isLoadHistory"></history-list>
	</div>
</template>

<script>
	import HistoryList from '../../components/HistoryList.vue'

	export default {
		data() {
			return {
				id: '',
				isLoadHistory: 0,
			}
		},
		methods: {
			//加载历史记录列表
			loadHistoryList() {
				this.isLoadHistory = 1;
			},
		},
		mounted() {
			this.id = this.$route.query.id;
		},
	}
</script>
2. 子组件

子组件接收父组件的参数,并且监听接收的load参数变化,在load参数等于1的情况下触发列表方法的调用。

<template>
	<div>
		<el-table :data="historyList" stripe>
            <el-table-column prop="name" label="姓名" min-width="8%"></el-table-column>                 
            <el-table-column prop="orderNo" label="订单编号" min-width="10%"></el-table-column>
            <el-table-column prop="createAt" label="创建时间" min-width="12%"></el-table-column>
            ...           
        </el-table>
	</div>
</template>
<script>
	import { ajax } from '../../api/api.js'
	export default {
		props: ['id', 'load'], 
		data() {
			return {
				historyList: [],
			}
		},
		watch: {
            load: function(newValue, oldValue) {
                if (newValue == 1) {
                    this.getHistoryList();
                };
            }
        },
		methods: {
			//历史记录列表
			getHistoryList() {
                let url = '/historyList.do';
                let param = {
                    id: this.id
                };

                ajax(url, param).then(response => {
                    if (response.code == 0) {
                        this.historyList = response.data.rows;
                    } else {
                        this.$message({
                            message: response.desc,
                            type: 'warning'
                        });
                    };                              
                });
            },
		},
		mounted() {
			this.id = this.$route.query.id;
		},
	}
</script>

注:如果父组件向子组件传递的参数为多个,可以组合成对象的形式,例如将id替换成obj即可。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值