Reputation: 115
I'm using watch
to track the input element value, which fires every time the value changes. Is there a way to call watch
explicitly?
like:
click Event --> isDataChanged --> call watch --> returns true if ref changed
<template>
<input type="text" v-model="userInput" />
<button @click="isChanged">change</button>
<p></p>
</template>
<script>
import { watch, ref } from "@vue/runtime-core";
export default {
setup() {
const userInput = ref("");
const isChanged = ()=> {
// call watch function
console.log("changed")
}
watch([userInput], (newValues, prevValues) => {
if (newValues) {
console.log(newValues)
return true;
}
});
return {
userInput,
isChanged,
};
},
};
</script>
Upvotes: 2
Views: 1647
Reputation: 138286
You could factor out the watcher into a separate function that isChanged()
could call when needed:
const userInput = ref('');
let lastNewValue = null;
let lastPrevValue = null;
const onUserInputChanged = (newValues = lastNewValue, prevValues = lastPrevValue) => {
lastNewValue = newValues;
lastPrevValue = prevValues;
if (newValues !== prevValues) {
return true;
}
};
const isChanged = () => {
const changed = onUserInputChanged();
console.log(changed ? 'changed' : 'no change');
};
watch(userInput, onUserInputChanged);
Upvotes: 2