0
votes

Standard example of component in Vue looks like that:

Vue.component('blog-post', {
  // camelCase in JavaScript
  props: ['postTitle'],
  template: '<h3>{{ postTitle }}</h3>'
})

In basic docs about components there's no data object used, just props. However documentation of data mentions components:

Restriction: Only accepts Function when used in a component definition.

There's even example:

var data = { a: 1 }

// direct instance creation
var vm = new Vue({
  data: data
})
vm.a // => 1
vm.$data === data // => true

// must use function when in Vue.extend()
var Component = Vue.extend({
  data: function () {
    return { a: 1 }
  }
})

Does it mean that component can have both data and props? Is data kind of private property (if we'd like to compare to OOP) and property public one?

1
They can have both, props are received by the parent component while data are manipulated by the component. The props are static (changeable by the parent) while data are dynamic (but cannot be changed by the parent).Karl-André Gagnon
Great. Could you please make it an answer :)?Arkadiusz Kałkus
@Karl-AndréGagnon I always change props value in component ! Is this good practice ?David Jaw Hpan
@DavidJorHpan it is not a good practice and Vue shouldn't allow you to do so. Don't you see an error message in the console (like this exemple: jsfiddle.net/6yyqzog8)Karl-André Gagnon
@Karl-AndréGagnon I do only on prop type array or object , they don't show that console error ! For string type of prop , I use $emit !!David Jaw Hpan

1 Answers

2
votes

Components can have both props and data. The difference between them is that props are received by the parent component while data are manipulated by the component. The props are static (changeable by the parent) while data are dynamic (but cannot be changed by the parent).

The only way a child component can affect a property is by emitting events. The parent component can listen to those events and receive and receive anything in the payload argument. In the listener function, they can change their own data and the child property will be updated as well. This is known as the one-way data flow:

All props form a one-way-down binding between the child property and the parent one: when the parent property updates, it will flow down to the child, but not the other way around. This prevents child components from accidentally mutating the parent’s state, which can make your app’s data flow harder to understand.

Vue documentation

Here's a little schema if you're visual:

enter image description here