【问题标题】:Watching a computed attribute in VueJS在 VueJS 中查看计算属性
【发布时间】:2014-09-30 02:20:56
【问题描述】:

在我的项目中,我有一个表单,只有在填写某些字段时才能提交,所以我在我的 ViewModel 中创建了 canSubmit 函数:

var vm = new Vue({
    data: {
        experiments: [],
        genes: ""
    },
    el: "html",
    computed: {
        canSubmit: function () {
            switch (this.searchType) {
                case "":
                    return false;
                case "gene":
                    return this.genes.length > 0 && this.experiments.length > 0;
                default:
                    return false;
            }
        }
    }
});

我还有一个按钮,如果 canSubmit 返回 true,我想显示,还有一些 <inputs> 会更改数据模型:

<textarea v-model="genes" name="genes" id="gene_list"></textarea>
<select v-model="experiments" name="experiments" multiple id="select_result_exps">
   <!--Various <options>-->
</select>
<button name="query" v-if="canSubmit" value="search" type="submit"">Submit</button>

所以当我更改 textarea 或 select 时,我的模型会更新,这意味着 canSubmit 返回 true。但是按钮不知道canSubmit 已更改,因此仍然不可见。

有没有办法观察派生的属性或方法以使其工作?或者我可以强制按钮重新检查其绑定吗?

【问题讨论】:

  • 如果你设置一个简单的 jsfiddle.net 可能更容易解决问题

标签: javascript mvvm vue.js


【解决方案1】:

这在最新的 0.11 版本中可以正常工作!

【讨论】:

  • 这是我错过了前几次阅读文档的“依赖收集陷阱”。您能否为每个计算属性制作一个正式的依赖关系列表?
  • 另外最新的版本是 v0.10.6,这是我正在使用的。
  • @Miguel 0.11-rc 可以在 github 上的自己的分支中找到。最新的发展发生在“下一个”分支中。 0.11.0 即将推出。在 0.11 中,您不再需要在计算属性中列出依赖项。
【解决方案2】:

我的代码不起作用的真正原因是绑定到 textarea 和 select 的变量不被视为 canSubmit 计算属性的依赖项。

我在documentation here 中发现了这一点。

在网站上的解决方案是最初访问这些变量,例如

enableSubmit: function () {
    this.genesString; //Adding these
    this.gene_search.experiments; //lines fixed the problem 

    switch (this.search_type) {
        case "gene":
            return this.genesString.length > 0 && this.gene_search.experiments.length > 0;
        case "experiment":
            return this.experiment_search.experiment.length > 0;
        default:
            return false;
    }
},

【讨论】:

    猜你喜欢
    • 2021-05-16
    • 2017-08-23
    • 2017-08-08
    • 2020-02-05
    • 2018-02-21
    • 2018-01-02
    • 1970-01-01
    • 2019-02-11
    • 2019-03-31
    相关资源
    最近更新 更多