简体   繁体   English

如何强制执行手表?

[英]How to force a watch execution?

I have an Array of strings which I filter though an input.我有一个字符串数组,我通过输入进行过滤。 The value of this input is watched, and the new filtered Array is created upon changes in the input value.监视此输入的值,并根据输入值的更改创建新的过滤数组。 This works fine.这工作正常。

Independently of this I have a switch toggle which changes the way the filtering works, by modifying the function in the watch.与此无关,我有一个开关切换,它通过修改手表中的 function 来改变过滤的工作方式。

My problem: toggling this switch is not taken into account until the moment the input changes again.我的问题:直到输入再次更改时才考虑切换此开关。 This is normal and expected: the watched value did not change.这是正常的和预期的:观察值没有改变。

Is there a way to:有没有办法:

  • either force the execution of a watch function (in which case I would also watch the toggle)要么强制执行watch function (在这种情况下,我也会观看切换)
  • or use an OR construction in the watch ("if either the input or the toggle change, do this and that...")或在手表中使用OR结构(“如果输入或切换发生变化,请执行此操作...”)

What do right now is to have one extra method that does the filtering, that is called on the input or slider change.现在要做的是使用一种额外的method进行过滤,即在输入或 slider 更改上调用。 This works but I am wondering whether there is a better way to cleverly slim down the code.这可行,但我想知道是否有更好的方法来巧妙地精简代码。

One way would be to use computed property to return filtered Array.一种方法是使用computed属性返回过滤后的数组。 No need to use watch .无需使用watch Computed properties are just for that occasions计算属性仅适用于这种情况

If you want to use watch :如果你想使用watch

  1. create a method that does the filtering.创建一个执行过滤的method
  2. Fire this method in a watcherwatcher中触发此method
  3. Fire it when toggle change. toggle时触发它。

Two working solutions, but computed would work better.两个可行的解决方案,但计算会更好。

You definitely should use a computed property instead of watch in this case.在这种情况下,您绝对应该使用computed属性而不是watch

computed: {
    computedArray() {
        let result = [];

        // your filtering code that include switch toggle

        return result;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM