seeman
seeman

Reputation: 115

call vue 3 watch function explicitly from another function

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

Answers (1)

tony19
tony19

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);

demo

Upvotes: 2

Related Questions