Vue父组件数据变化子组件不能及时响应的解决办法【watch监听】


一、前言

  1. watch监听,根据被监听的属性是 还是 对象,可以分成以下两种解决办法

二、解决方法

1.针对父组件传入的是值的情况

假设父组件有三个随时变化的值 page、size、total

<template>
	<div>
		<Pagination :page="page" :size="size" :total="total" ></Pagination>
	</div>
</template>

<script>
	import Pagination from '../component/pagination';
	export default {
	  name: 'MuluList',
	  components: {Pagination, },
	  data() {
	      return {
			  page: 1,
			  size: 10,
			  total: null,
	      }
	  }
	}
</script>

子组件中添加watch方法,监听父组件 page、size、total ,及时响应更新页面

<template>
	<div>
		<label>{{currentPage}}</label>
		<label>{{currentSize}}</label>
		<label>{{currentTotal}}</label>
	</div>
</template>

<script>
	export default {
		name: 'Pagination',
		props: ["page", "size", "total"],
	    methods: {

	    },
	    
	    // ---------------------------------------------------------
		// 在子组件中watch是用来监听props的监听器,只需要给要监听的props属性在watch声明同名的方法,即可监听对应data属性的变化.
		watch: {
			page(){
				this.currentPage = this.page
				this.currentSize = this.size
				this.currentTotal = this.total
			}
		},
		// ----------------------------------------------------------
	    
	    data() {
	      return {
	        currentPage: this.page,
	        currentSize: this.size,
	        currentTotal: this.total
	      }
	    }
	  }
</script>

2.针对父组件传入的是对象的情况

假设父组件有一个随时变化的对象 pageData

<template>
	<div>
		<Pagination :pageData="pageData" ></Pagination>
	</div>
</template>

<script>
	import Pagination from '../component/pagination';
	export default {
	  name: 'MuluList',
	  components: {Pagination, },
	  data() {
	      return {
			  pageData: {
			      page: 1,
			      size: 10,
			      total: null
			  }
	      }
	  }
	}
</script>

子组件中添加watch方法,监听父组件 pageData 对象中的值,及时响应更新页面

<template>
	<div>
		<label>{{currentPage}}</label>
		<label>{{currentSize}}</label>
		<label>{{currentTotal}}</label>
	</div>
</template>

<script>
	export default {
		name: 'Pagination',
		props: ["pageData", ],
	    methods: {

	    },
	    
	    // ---------------------------------------------------------
		// 在子组件中watch是用来监听props的监听器,只需要给要监听的props属性在watch声明同名的方法,即可监听对应data属性的变化.
		watch: {
			page(){
				this.currentPage = this.pageData.page
				this.currentSize = this.pageData.size
				this.currentTotal = this.pageData.total
			}
		},
		// ----------------------------------------------------------
	    
	    data() {
	      return {
	        currentPage: this.pageData.page,
	        currentSize: this.pageData.size,
	        currentTotal: this.pageData.total
	      }
	    }
	  }
</script>
评论 23
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

什么都干的派森

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值