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>