Common Vue Problems — Emit Event from Parent to Child, Watcher Variables, and More
Vue.js makes developing front end apps easy. However, there are still chances that we’ll run into problems.
In this article, we’ll look at some common issues and see how to solve them.
Access Variables in the Watcher
We can access variables in a watcher just like we do with other methods.
For instance, we can write:
watch: {
dates: {
handler(date) {
if (date.start) {
this.params.from = new Date(date.start).toString()
}
if (date.end) {
this.params.to = nbew Date(date.end).toString()
}
},
deep: true
}
}
We get the value of the dates
object in our watcher and we can do stuff with it.
deep
set to true
means that we watch all properties of an object.
Create Vue.js Slot Programmatically
There’s no documented way to create slots programmatically.
However, we can use a render function to create elements with the slot attribute.
For instance, we can write:
Vue.component('parent', {
render (createElement) {
return createElement('child', [
createElement('h1', { slot: 'parent' }, 'parent slot'),
createElement('p', { slot: 'default' }, 'default slot')
])
}
})
Then we can use it by writing:
Vue.component('child', {
template: '<div><slot name="parent-slot" /><slot /></div>'
})
We can create elements with createElement
which can include the slot
attribute to create named and default slots.
Getting the Value of the key Prop
We can’t get the value of the key prop in our child elements.
Instead, we have to call it something else.
key
is a special prop that’s used by Vue to keep track of components and elements rendered with v-for
.