[Vuejs]-Call function inside data() property

0👍

When using this, you try to call on a member for the current object.

In JavaScript, using the {} is actually creating a new object of its own and therefore, either the object needs to implement onNodeSelected or you need to call a different function that will allow you to call it on an object that implements the function.

export default {
    name: 'SideNavMenu',
    data () {
        return {
            searchValue: '',
            treeData: this.getData(), // <--- This
            treeOptions: {

            fetchData(node) {
                this.onNodeSelected(node) // <--- and this
            }
        },
    }
},


//are calling functions in this object :
{
    searchValue: '',
    treeData: this.getData(),
    treeOptions: {
    fetchData(node) {
        this.onNodeSelected(node)
    }
},
//instead of the object you probably are thinking

I would avoid creating object blocks within object blocks like those as the code quickly becomes unreadable and rather create functions within a single object when needed.

I am guessing you would have the same error message if you tried to get a value from treeData as well

0👍

You are not calling the function, or returning anything from it. Perhaps you’re trying to do this?

export default {
 name: 'SideNavMenu',
 data () {
  return {
      searchValue: '',
      treeData: this.getData(),
      treeOptions: fetchData(node) {
          return this.onNodeSelected(node)
      },
  }
},

Regardless, it is not considered good practice to put functions inside data properties.
Try declaring your variables with empty values first, then setting them when you get the data inside beforeCreate, created, or mounted hooks, like so:

export default {
  name: 'SideNavMenu',
  data () {
    return {
      searchValue: '',
      treeData: [],
      treeOptions: {},
    }
  },
  methods: {
    getData(){
      // get data here
    },
    fetchData(node){
       this.onNodeSelected(node).then(options => this.treeOptions = options)
    }
  },
  mounted(){
     this.getData().then(data => this.treeData = data)
  }
},

Or if you’re using async await:

export default {
  name: 'SideNavMenu',
  data () {
    return {
      searchValue: '',
      treeData: [],
      treeOptions: {},
    }
  },
  methods: {
    getData(){
      // get data here
    },
    async fetchData(node){
       this.treeOptions = await this.onNodeSelected(node) 
    }
  },
  async mounted(){
     this.treeData = await this.getData()
  }
},

Leave a comment