uniapp——watch监听某个值如果有变化则运行指定的方法、this.$store

本文介绍如何使用Vue.js的watch特性来监听数据变化并作出响应,包括局部数据和全局store的状态改变。

1、监听当前页面的变量改变

watch监听watchData值,如果有变化则运行cancel方法

代码如下:

<template>
	<view class="container">
		<view class="" @click="confirm">
			<image mode="widthFix"
				src="https://images.weserv.nl/?url=https://wx1.sinaimg.cn/mw2000/006Z6VeYly8fl0aq020yjj30ku0ktdha.jpg"
				@error="imageError"></image>
		</view>
	</view>
</template>

<script>
	export default {
		watch: {
			watchData: {
				handler(newName, oldName) {
					this.cancel()
				}
			}
		},
		data() {
			return {
				watchData: true,
			}
		},
		onLoad() {

		},

		methods: {
			confirm: function() { //确定按钮
				console.log('您点击了确定按钮');
				this.watchData = !this.watchData; //改变watchData的值
			},
			cancel: function() { //取消按钮
				console.log('您点击了取消按钮');
			},

		},
		
	}
</script>

<style scoped>
	car-list {
		width: 100%;
	}
</style>

2、监听全局store的变量改变(this.$store)

 

步骤一:配置全局都能this.$store

store.js代码

import Vue from 'vue'
import Vuex from 'vuex'
 
Vue.use(Vuex)
const store = new Vuex.Store({
  state: {
    count: 1
  },
  getters: {
    changeCount: state => {
      return state.count + 1
    }
  },
  // 同步
  mutations: {
    add (state,count) {
      state.count = state.count + count
	  // console.log("state", state)
    }
  },
  // 异步
  actions: {
    addFun (context, n) {
      context.commit('add', n)
    }
  }
})
export default store

在main.js引入store.js,并且挂载store

 步骤二:index.vue和index2.vue里面的方法

index.vue代码:

<template>
	<view class="content">
		<image class="logo" src="/static/logo.png" @click="bindImg"></image>
		<navigator url="../index2/index2">
		<view class="text-area"  >
			<text class="title">{{title}}</text>
		</view>
		</navigator>
	</view>
</template>

<script>
	export default { 
		// 监听store.state.count的值是否改变
		watch:{
			"$store.state.count": function(val, oldval) {
					this.test11()
				}
		},
		data() {
			return {
				title: 'Hello'
			}
		},
		onLoad() {

		},
		methods: {
			bindImg() {
				console.log("点击图片",this.$store.state.count)				
				// this.$store.commit("add",3)//调用mutations里的add方法
			},
			test11(){
				console.log("监听到store里变量已经改变,运行此方法")				
			}
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>

index2.js代码:

<template>
	<view>
	<view class="" @click="clickA">
		我是第二页面
	</view>
		
	</view>
</template>

<script>
	export default {
		data() {
			return {
				
			}
		},
		methods: {
			clickA(){
				this.$store.commit("add",5)////调用mutations里的add方法,改变state的值
			}
		}
	}
</script>

<style>

</style>

`this.$store.watch` 是 Vue.js 中用于监听 Vuex Store 数据变化方法之一。通过该方法可以实现对特定状态或者 Getter 变化进行响应式操作。 以下是 `this.$store.watch` 的具体使用说明和示例: ### 方法定义 `this.$store.watch(fn, callback, options)` - **fn**: 可以是一个函数,也可以是字符串形式的 Getter 名称。如果传递的是函数,则会接收到两个参数:Store 的 State 和 Getters。 - **callback**: 当被监视的数据发生变化时触发的回调函数。 - **options**: (可选)对象参数,支持与 Vue 的 `$watch` 类似的行为控制选项,比如 `{ deep: true }` 或者 `{ immediate: true }`[^5]。 ### 示例代码 #### 示例 1:监听单个状态 ```javascript // 在组件内部使用 this.$store.watch 来监控 state.count 的变化 this.$store.watch( (state) => state.count, (newVal, oldVal) => { console.log(`count changed from ${oldVal} to ${newVal}`); }, { deep: false } ); ``` #### 示例 2:监听多个状态 ```javascript // 同时监听多个状态 this.$store.watch( (state) => ({ count: state.count, doubleCount: state.doubleCount }), (newValue, oldValue) => { console.log('New Value:', newValue); console.log('Old Value:', oldValue); }, { deep: true } ); ``` #### 示例 3:监听 Getter ```javascript // 监听某个 Getter 的变化 this.$store.watch( 'doubleCount', // 这里可以直接写 Getter 的名称 (newVal) => { console.log('Double Count Changed To:', newVal); } ); ``` #### 示例 4:立即执行回调 ```javascript // 设置 immediate: true 让回调在初始化时也执行一次 this.$store.watch( (state) => state.count, (newVal) => { console.log('Current Count is:', newVal); }, { immediate: true } ); ``` --- ### 注意事项 1. 如果需要深层嵌套的状态监测,请设置 `deep: true` 参数来启用深度检测。 2. 对于简单状态的变更,推荐优先考虑 Vuex 提供的 Mutation 和 Action 而非频繁依赖 Watcher。 3. 使用完毕后可以通过返回取消监听器注册,防止内存泄漏: ```javascript const unwatch = this.$store.watch(...); unwatch(); // 手动解除监听 ``` ---
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

wy313622821

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

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

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

打赏作者

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

抵扣说明:

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

余额充值