Boris K
Boris K

Reputation: 3580

Vue: initial triggering of a computed property

In my Vue component, I have a computed property which watches the state and the component, and returns an object.

        currentOrganization () {
            if (this.$store.state.organizations && this.selectedOrganization) {
                return this.$store.state.organizations.filter(org => org.id === this.selectedOrganization)[0];
            }
        }

Unfortunately, this property does not update automatically when the component loads, though I can see that I have both this.$store.state.organizations and this.selectedOrganization. It does, however, update when I dispatch an action to my Vuex store via the select component below:

                <b-form-select id="orgSelect"
                               v-model="selectedOrganization"
                               :options="this.$store.state.organizations.map(org => {return {value: org.id, text:org.name}})"
                               size="sm"
                               v-on:input="currentOrganizationChange()"
                               class="w-75 mb-3">
                    <template slot="first">
                        <option :value="null" disabled>Change Organization</option>
                    </template>
                </b-form-select>

The component dispatches a Vuex action:

            currentOrganizationChange () {
                this.$store.dispatch('setCurrentOrganization', this.selectedOrganization);
            },

How can I make currentOrganization() compute initially?

Upvotes: 2

Views: 2113

Answers (2)

gleam
gleam

Reputation: 870

The computed will not calculate until you use it.

console.log it, or just write current organization; somewhere in code which executes and it will calculate :)

Upvotes: 4

Tristan Shelton
Tristan Shelton

Reputation: 490

You should ensure that your computed always returns a value. A linter would have warned you of that error. Chances are your condition is failing -- perhaps this.selectedOrganization is falsy.

Upvotes: 0

Related Questions