【问题标题】:call vue 3 watch function explicitly from another function从另一个函数显式调用 vue 3 watch 函数
【发布时间】:2022-01-08 07:06:19
【问题描述】:

我使用watch 来跟踪输入元素值,每次值更改时都会触发该值。有没有办法显式调用watch

喜欢:

点击事件 --> isDataChanged --> 调用 watch --> 如果 ref 改变则返回 true

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

【问题讨论】:

    标签: vue.js vuejs3 vue-composition-api vue-reactivity


    【解决方案1】:

    您可以将观察者分解为一个单独的函数,isChanged() 可以在需要时调用:

    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

    【讨论】:

      猜你喜欢
      • 2015-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      • 2017-08-04
      相关资源
      最近更新 更多