【问题标题】:re-populate a directive array reactively in Vue.js在 Vue.js 中反应性地重新填充指令数组
【发布时间】:2021-07-10 09:24:12
【问题描述】:

我在 data() 中定义了一个数组,该数组通过其绑定挂钩中的自定义指令填充,如下所示:

import Vue from 'vue'
export default {
el: '#showingFilters',
name: "Filters",
data() {
    return {
        country: '' // v-modelled to a <select>
        states: [],
    }
},
directives: {
    arraysetter: {
        bind: function(el, binding, vnode) {
            vnode.context[binding.arg] = Object.keys(el.options).map(op => el.options[op].value);
        },
    },
},
methods: {
    countryChangeHandler() {
        this.states.splice(0)
        fetch(`/scripts/statejson.php?country=${this.country}`)
            .then(response => response.json())
            .then(res => {
                res.states.forEach( (element,i) => {
                    Vue.set(this.states, i, element.urlid)
                });
            })
    },
}

当我想在countryChangeHandler() 方法中重新填充states 数组时,问题就开始了(当国家选择标签发生@change 时)。 我先使用splice(0) 使数组为空,然后我使用Vue.set 使重新填充反应,但Vue 仍然不知道!该数组具有正确的元素!我只是不知道如何使这个反应。

PS:我在没有 forEach 的情况下搜索过,但 $set 需要索引。

如果有任何帮助,我将不胜感激。

【问题讨论】:

  • 不太确定使用自定义指令的动机是什么,因为您只显示了部分代码。除非您真的需要自定义指令,否则请尝试更新 this.states = res.states。然后,您可以将“地图”功能移动到计算属性。如果你没有得到解决,在某个时候考虑创建一个 CodeSandbox。
  • 并非所有国家都有州

标签: javascript arrays vue.js vuejs2


【解决方案1】:

此解决方案应该有效并保持反应性。

  1. 您应该能够在不使用spliceset 的情况下替换整个数组。

  2. 我使用闭包来捕获 this,因为有时 fetch 调用会干扰 this 引用,即使在 lambda 表达式中也是如此。

countryChangeHandler() {
        this.states = []
        const that = this
        fetch(`/scripts/statejson.php?country=${this.country}`)
            .then(response => response.json())
            .then(res => {
                that.states = res.states.map(it=>it.urlid)              
            })
    },

【讨论】:

    猜你喜欢
    • 2020-02-18
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-12
    • 2017-03-19
    • 1970-01-01
    相关资源
    最近更新 更多