方法1:为模块或组件创建 key
目前 uni-app 还无法使用类似 Vue 中的 watch 方法来监听数据变化以更新视图,也无法监听 data 中数组或对象的变化。

所以碰到需要动态更新数据,刷新页面或组件视图时,需要使用 key 属性来刷新,代码示例如下:

<template>
	<view>
		<view class="module-box1" :key="moduleKey"></view>
		<commponent1 v-if="PageCur=='commponent1'" :key="commponent1Key"></commponent1>
		<commponent2 v-if="PageCur=='commponent2'" :key="commponent2Key"></commponent2>
		
		<view class="module-box2">
			<button	@tap="tapMenu" :data-cur="commponent1">按钮1</button>
			<button	@tap="tapMenu" :data-cur="commponent2">按钮1</button>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			PageCur: 'commponent1',
			moduleKey: 0,
			commponent1Key: 0,
			commponent2Key: 0,
			
			},
		};
	},
	onLoad() {
		//获取数据
		this.getData()

	},
	methods: {
		getData() {
			var that = this
			//获取数据
			uni.request({
			    url: 'https://www.example.com/request',
			    success: (res) => {
			        console.log(res.data);
			        //相关处理
					//最后更新相应模块或组件的key
					++that.moduleKey
					++that.commponent1Key
					++that.commponent2Key
			    }
			});
			
		},
		tapMenu(e) {
			var that = this
			this.PageCur = e.currentTarget.dataset.cur
		},
}
</script>

数据处理完成后,通过修改 key 的值变可以刷新该模块或组件,前提是为该模块或组件设置了 key 属性
 

方法2:this.$forceUpdate()

this.$forceUpdate();进行强制渲染,效果实现。搜索资料得出结果:因为数据层次太多,render函数没有自动更新,需手动强制刷新。

方法3:splice更新数组刷新页面

直接对数组元素赋值,是不会更新视图的。要使用arr.splice()方法更新数组,才会更新视图
代码如下:

<template>
 <div>
      <ul>
          <li v-for="(item,i) in arr">{{item}}</li>
      </ul>

      <button @click="wrong">失效</button>
      <button @click="correct">生效</button>
 </div>
 </template>
 <script>
 export default {
   name: "Home",
   data () {
     return {
         arr:[1,2,3]
     };
   },
   methods: {
       wrong(){
           this.arr[0] = 9;   // 视图不会更新,页面上还是1,2,3
       },

       correct(){
           this.arr.splice(0,1,9); // 视图更新了,页面上是9,2,3
       }
       
   },
 }
 </script>
 <style lang="css" scoped>
 </style>

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐