Viewing a computed attribute in VueJS
In my project, I have a form that can only be submitted when certain fields are filled, so I created a canSubmit function in my ViewModel:
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;
}
}
}
});
I also have a button that I want to show if canSubmit returns true, and some <inputs>
that change the data model:
<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>
So when I change the textbox or selection, my model updates, which means it canSubmit
returns true. However, the button does not know what canSubmit
has changed, so it remains invisible.
Is there a way to look at a derived attribute or method to get this to work? Alternatively, can I force the button to recheck its bindings?
source to share
The real reason my code didn't work was because the variables bound to textarea and select were not considered dependent on the computed canSubmit property.
I found this in the documentation here .
The solution, as on the site, was to access these variables first, eg.
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;
}
},
source to share