Vue Data function - Multiple ways to declare


Each component has data function methods as part of declaration.

data is an function that returns an object.

Why data has to declare in a component?

Each component has some data to show in the browser, so data function code returns the data. this will be accessed by Component methods globally.

Does data function holds API logic to retrieve from Database? No, data fetching logic should be handled in method section of component.

When will data function is called? data function is called by Vue while creating component instance and returns an object, These data includes in Vuejs reactive and store the instance data as $data object.

Important points about data function

  • It can be arrow functions or data property or normal es5 function
  • It should always return an object
  • Object properties are available, can be accessed using component instance
  • Methods can be called inside data function
  • returned object contains properties,keys as well as function calls
Vue.component('About', {
  template: '<div>About Component</div>',

  data: function() {
    return {
     faq:"Vuej component faqs"    }
  }
});

Following are different ways to declaring data function in vue components

  • data using ES6 arrow functions
  • data object return
  • data es5 style functions

why vuejs data should be function than an object

In this blog post, We are going to learn multiple ways to define data function in vuejs component with examples

data arrow functions in vuejs

arrow functions are introduced in ES6 JavaScript language. Vue components can be declared with data arrow function as seen below

Arrow functions are new way declaring using()=> syntax. these functions wont have this context inside it. What does mean it? Inside function, this.HelloWorld props object not returns Component props, **this** represents current window scope not component scope, The this.componenent throws below error to console as these are bound to parent context.

Uncaught TypeError: Cannot read property ‘InputBlurExample’ of undefined

export default {
    props: ['HelloWorld'],
    data: () => ( {
      name: 'Franc',
      data: this.HelloWorld // undefined
    })
}

return keyword returns the object in the data function

The same way can be returned using implicit return syntax

export default {
    props: ['HelloWorld'],
    data: () => ({
      name: 'Franc',
      data: this.HelloWorld // undefined
    })
}

data object without function

Declared data object rather function and initialized with 0 value, property in data are shared by multiple component instances.

what is the issue here? if these component is used in five places, that values are different for each component usage. This is only drawback.

export default {
    props: ['HelloWorld'],
    data:{
      increment:0,
    }
}

data function object

Every component shares data object, if you declare the data as function, It very easy mutate the state

export default {
    props: ['HelloWorld'],
    data: function(){
        return {increment:0},
    }
}

This is ES5 way of declaring function in javascript

The same can be trimmed with little coding

export default {
    props: ['HelloWorld'],
    data: {
        return {increment:0},
    }
}

export default { name: “InputBlurExample”, data() { }, methods: { blurEvent: function (e) { const email = e.target.value; console.log(email); }, }, }; data in vuejs return the f data: () => { return { stripe: null, stripePK: stripePK, … } }

How to call methods in data function

data function returned object contains functions which can instance methods

This will be very useful when you are calling other components event handlers in parent child components,

In data function, store the current vue component instance using this in a variable and call the method.

export default {
  name: "InputComponent",
  data() {
    var self = this;
    return {
      onClick: function () {
        self.mymethod();
      },
    };
  },

  methods: {
    mymethod: function () {},
  },
};
</script>

Conclusion,

On this blog post, You learned multiple approaches to create a data function and returns an object.

I hope you learned new things with this.

THE BEST NEWSLETTER ANYWHERE
Join 90,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts