Consider a VueJS app that allows for showing / editing blogposts.
prop
to the modal-component. data
object on the Modal-component that acts as the model to populate the form fields, and vice-versa, be updated when the user changes the form fields. The problem: How do I connect the blogpost which is passed as a prop
to the data
field of the modal-component so that:
What's the correct Vue way to accomplish this?
To specify the type of prop you want to use in Vue, you will use an object instead of an array. You'll use the name of the property as the key of each property, and the type as the value. If the type of the data passed does not match the prop type, Vue sends an alert (in development mode) in the console with a warning.
. sync is a shorthand for binding a variable (myVar) to a component property ('prop1' in this case) and listening to the 'update:prop1' event emitted from the component to update the variable 'myVar'.
Using props in VueAfter you have set up the props, you can then use it inside your component as though the data was defined inside the same component. This means you can set up method calls and easily access this.
There are only three different ways to share data across the VueJs components, it depends on you which technique is better for you to solve your problem. Using props share data from parent to child. Using Event Emitting custom events to share data from child to parent.
You have three (at least) ways of doing it:
1) Connect the data via the prop
attribute, just as you are doing, but add the .sync
attribute to it. This way, when the data is modified on the form, it automatically gets modified too on the component. The problem with this solution is that the update is automatic, so if a validation fails, or the user closes the modal without saving the changes, these are saved anyway. An example: https://jsfiddle.net/Lz3aq64f/
2) The other way of doing it is getting the modal to $dispatch
an event with the saved information when it's saved. The blogpost element should listen for this event and act accordingly.
On the modal:
this.$dispatch('update-post', this.title, this.author);
On the blogpost:
this.$on('update-post', function(title, author) {
this.title = title;
this.author = author
});
If the blogpost component and the modal component are not in the same hierarchy, things get a little bit more complicated, and probably you need the common parent element to act as a proxy. Think of the modal
element dispatching
the information up, the #app
element catching it via $on
, and then doing $broadcast
to the blogpost
element.
3) Use something like vuex
to act as a central repository of state. I don't know how big is your application, but this would be the cleanest way to go: http://vuex.vuejs.org/en/index.html
Good luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With