0
votes

hello guys i found that i can return data but few things create confusion can anybody tell is this method is correct or not

method 1:

  <script>
      export default {
         data () {
            return {
                     nav: [],
                   }
            },
   mounted () {
             this.checkSidebarVisibility()
           },
   methods: {
           checkSidebarVisibility: function() {
            this.nav= navnew
      } 
  },
</script>

i know this method is 100% correct but when i use this method i faced problem like data is loading too late for eg :- if i use this method for select drop down then dat in select option after few second (atleast 3 sec)

method 2:

i have little confusion is this method is correct way in vue for eg:

  <script>
     export default {
          data () {
            return {
                     nav: this.checkSidebarVisibility(),
                   }
            },

   methods: {
           checkSidebarVisibility: function() {
            this.nav= navnew
      } 
   },
 </script>

i found this method load data quicky in select option as well as work fluent i.e without any error in browser console but i confused that is this correct way of vue can any expert can give any suggestion

1

1 Answers

0
votes

If you want to set some property of data as soon as possible, use created() instead of mounted(). That is because created() is the earliest lifecycle hook where the data has been initialized.

<script>
  export default {
    data() {
      return {
        nav: [],
      }
    },
    created() {                        // using created() instead of mounted()
      this.checkSidebarVisibility()
    },
    methods: {
      checkSidebarVisibility: function() {
        this.nav = navnew
      }
    },
    // ...
  }
</script>

If, on the other hand, your code that fills the data is asynchronous, e.g. an ajax call, you could dispatch the request from an even earlier hook, the beforeCreate():

<script>
  export default {
    data() {
      return {
        nav: [],
      }
    },
    beforeCreate() {                  // using beforeCreate() instead of created()
      this.checkSidebarVisibility()   // assuming it is async, e.g. ajax
    },
    methods: {
      checkSidebarVisibility: function() {
        this.nav = navnew
      }
    },
    // ...
  }
</script>

This is possible because the initialization of Vue is synchronous, meaning even if your async operation (ajax) dispatched at beforeCreate() returns instantly, the data will already have been initialized (something that happens between the beforeCreate and created hooks).