Vue父组件数据变化子组件不能及时响应的解决办法【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>

猜你喜欢

转载自blog.csdn.net/weixin_43721000/article/details/128717354
今日推荐