简体   繁体   中英

Vue use computed property in data

I have the following const properties in my Vue data.

 <script>
import { mapGetters, mapActions } from 'vuex'
export default {
data() {
    const properties = ['Property 1', 'Property 2']
    return {
        properties,
        form: propertyNames.map(name => ({ property_type: [] })),
    }

  },

I however am computing the properties in a computed property as follows

computed: {
 
     properties() {
            const properties = this.property_form.property_name;
            const filtered = properties.filter(p => p != null)

            return filtered;
        }
},

so I want to use the computed property in the data as follows:

 <script>
import { mapGetters, mapActions } from 'vuex'
export default {
data() {
    const properties = this.properties
    return {
        properties,
        form: propertyNames.map(name => ({ property_type: [] })),
    }

  },

but when I do this, I get the error Property or method "properties" is not defined on the instance .

data() is invoked before computed props are resolved, so you can't reference computed props from there.

I assume this question is related to your other question , where form needs to be used in v-model . Since form depends on the computed prop, you should use a watcher on the computed prop that updates form accordingly:

export default {
  data() {
    return {
      form: []
    }
  },
  computed: {
    properties() {/*...*/},
  },
  watch: {
    properties(properties) {
      this.form = properties.map(_ => ({ property_type: [] }))
    }
  }
}

What is const properties = ['Property 1', 'Property 2'] ?

Pretty sure you cannot have it nested inside of data . Move it to the upper scope maybe or define it directly like

data() {
  return {
    properties: ['Property 1', 'Property 2']
  }
}

Also, it's not very clear as of what you're trying to achieve here. A lot of things are mixed together. You're not really supposed to make a map in data since it's here for raw data (as it's called).

Here is the official documentation on computed properties , maybe give it a second read or update your question by explaining a bit better what is happening here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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