vue reactivity in list with slot scoped component - vue.js

Good afternoon!
I have a loop and inside each element I display a separate component that takes props and gives them through the slot. I can't figure out why when new elements are added the update hooks happen on the old ones?
Example:
have: 1 2 3
add: 4
log: created 4, updated 3, updated 2, updated 1
Why is this happening?
Vue.component('slot-component', {
inheritAttrs: false,
created() {
console.log('created', this._uid);
},
updated() {
console.log('updated', this._uid);
},
render(h) {
return this.$scopedSlots.default(this.$attrs);
}
})
new Vue({
el: '#app',
data() {
return {
list: []
}
},
methods: {
add() {
this.list.push({
title: 'some'
})
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.7.8/vue.min.js"></script>
<div id="app">
<div class="list">
<div
v-for="(item, n) in list"
:key="n"
class="list-item"
>
<slot-component
:title="item.title"
v-slot="props"
>
{{ props.title }}
</slot-component>
</div>
<button #click="add">add</button>
</div>
</div>
Update
Thanks to Raphael Rollet for clarifying that all array elements are updated when the array is changed globally. But then it is not entirely clear why this behavior behaves differently with a component that uses props
Pass and use props — not call updated
Vue.component('slot-component', {
props: ['title'],
created() {
console.log('created', this._uid);
},
updated() {
console.log('updated', this._uid);
},
template: `<div>{{ title }}</div>`
})
new Vue({
el: '#app',
data() {
return {
list: []
}
},
methods: {
add() {
this.list.push({ title: 'some' });
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.7.8/vue.min.js"></script>
<div id="app">
<div class="list">
<slot-component
v-for="(item, n) in list"
:key="n"
:title="item.title"
class="list-item"
>
</slot-component>
<button #click="add">add</button>
</div>
</div>
Pass and use props with slot — call updated
Vue.component('slot-component', {
props: ['title'],
created() {
console.log('created', this._uid);
},
updated() {
console.log('updated', this._uid);
},
template: `<div><slot>{{ title }}</slot></div>`
})
new Vue({
el: '#app',
data() {
return {
list: []
}
},
methods: {
add() {
this.list.push({ title: 'some' });
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.7.8/vue.min.js"></script>
<div id="app">
<div class="list">
<slot-component
v-for="(item, n) in list"
:key="n"
:title="item.title"
class="list-item"
>
{{ item.title }}
</slot-component>
<button #click="add">add</button>
</div>
</div>
Use $attrs — call updated
Vue.component('slot-component', {
created() {
console.log('created', this._uid);
},
updated() {
console.log('updated', this._uid);
},
template: `<div>{{ $attrs.title }}</div>`
})
new Vue({
el: '#app',
data() {
return {
list: []
}
},
methods: {
add() {
this.list.push({ title: 'some' });
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.7.8/vue.min.js"></script>
<div id="app">
<div class="list">
<slot-component
v-for="(item, n) in list"
:key="n"
:title="item.title"
class="list-item"
>
</slot-component>
<button #click="add">add</button>
</div>
</div>
Use slot — call updated
Vue.component('slot-component', {
created() {
console.log('created', this._uid);
},
updated() {
console.log('updated', this._uid);
},
template: `<div><slot></slot></div>`
})
new Vue({
el: '#app',
data() {
return {
list: []
}
},
methods: {
add() {
this.list.push({ title: 'some' });
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.7.8/vue.min.js"></script>
<div id="app">
<div class="list">
<slot-component
v-for="(item, n) in list"
:key="n"
:title="item.title"
class="list-item"
>
<template #default></template>
</slot-component>
<button #click="add">add</button>
</div>
</div>

The behaviour who seems "weird" is all time because vue binding.
You'r array is update so all property inside is update, someone can have a nice explanation on that because it's too deep.
But the solution is not use a update function on your child (if you don't want update something on every child), but set a watcher on what you want and do something in that case.
Like if you update a title on a child you do that:
watch: {
title(value) {
console.log(value)
}
}
Update:
For the two last example in your update section, like i explain for me it's expected, it's seems weird yes, but it's binding with vue.
About the first, you use a props so you pass a string in your component and nothing else. He have no reason to update.
For the second you do the same thing but with a slot, the only explanation for me it's, when you initialise a slot (even empty) the slot access to the parent data, and because binding is update.
I found this:
https://vuejs.org/guide/components/slots.html#render-scope
Slot content has access to the data scope of the parent component,
because it is defined in the parent.
Be honest it's assumption, if anyone have a other explanation i want to know it !

Related

How can I select element Id with a function in Vue.js?

I want to use the Id of the element in which I use the function as a parameter. Example:
<div
class="col-2 column-center"
id="myId"
#mouseover="aFunction(id)"
>
methods: {
aFunction(id){
alert(id);
}
}
But it doesn't work. How can I do it?
In another way, you can make your id attribute bind with the data property, like this :
<template>
<div class="col-2 column-center" v-bind:id="id" #mouseover="aFunction(id)">
test
</div>
</template>
<script>
export default {
name: 'Test',
data() {
return {
id: 'myId',
};
},
methods: {
aFunction(id) {
alert(id);
},
},
};
</script>
You can pass the event to the method and then get the id from event.target.id.
https://jsfiddle.net/tr0f2jpw/
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!'
},
methods: {
aFunction(event){
alert(event.target.id);
}
}
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<div
class="col-2 column-center"
id="myId"
#mouseover="aFunction($event)"
>
some stuff
</div>
</div>

How to make property in Vue component to be reactive

I'm trying to create a new component:
Vue.component('my-component', {
props: {
displayed: {
type: Boolean
}
},
template: `
<div v-bind:class="{'modal': true, 'auth-required': true, 'show-modal': displayed }">
<div class="modal__content">
<img src="/img/popup/close.svg" v-on:click="displayed = false;" alt="close" class="modal__closeBtn modal__closeBtn-questions" />
<slot></slot>
<img src="/img/popup/dog.png" alt="dog" class="modal__contentImg" />
</div>
</div>`,
data: function () {
return {
isDisplayed: this.displayed
};
},
})
But when i'm trying to bind displayed property to another property from the page it doesn't work when modal.authRequired value changes:
<mycomponent :displayed="modal.authRequired"></mycomponent>
How to make isDisplayed to be reactive when modal.authRequired changes
Add a watch to your prop:
Vue.component('my-component', {
props: {
displayed: {
type: Boolean
}
},
template: `
<div v-bind:class="{'modal': true, 'auth-required': true, 'show-modal': isDisplayed }">
<div class="modal__content">
<img src="/img/popup/close.svg" v-on:click="displayed = false;" alt="close" class="modal__closeBtn modal__closeBtn-questions" />
<slot></slot>
<img src="/img/popup/dog.png" alt="dog" class="modal__contentImg" />
</div>
</div>`,
data: function () {
return {
isDisplayed: this.displayed
};
},
watch: {
displayed(newValue) {
// Update the data value
this.isDisplayed = newValue;
}
}
})
Also, notice that I changed the 'show-modal' binding: 'show-modal': isDisplayed
Reactive properties are the computed one :https://v2.vuejs.org/v2/guide/computed.html

Vue resets child Component data on props update

I have child component, that has some internal data, that should not be changed from outside. But when I update prop from parent component, this internal data is reset.
Basically in example below, when we change title from outside, value is set back to empty ''. How can I make value persistent with Child component props update?
Child.vue
<template>
<div class="child">
<h2>{{title}}</h2>
<input type="text" :value="value" v-on:change="$emit('change', $event.target.value)">
</div>
</template>
<script>
export default {
props: {
title: {
default: 'Just title'
}
},
data() {
return {
value: ''
}
}
}
</script>
Parent.vue
<template>
<div class="parent">
<Child :title="title" v-on:change="processTitle($event)"></Child>
</div>
</template>
<script>
import Child from './Child';
export default {
data() {
return {
title: 'Title from parent'
}
},
methods: {
processTitle(value) {
this.title = value.reverse();
}
}
}
</script>
You are not setting the value data attribute, :value=value means that "if value changes, the input value should pick up that change". But value doesn't change. Use v-model instead if you want to keep it simple.
Vue.component("Child", {
props: {
title: {
default: 'Just title'
}
},
data() {
return {
value: ''
}
},
template: `
<div class="child">
<h2>{{title}}</h2>
<input type="text" v-model="value" v-on:change="$emit('change', $event.target.value)">
</div>
`
})
new Vue({
el: "#app",
data() {
return {
title: 'Title from parent'
}
},
methods: {
processTitle(value) {
this.title = value.split("").reverse().join("");
}
},
template: `
<div class="parent">
<child :title="title" v-on:change="processTitle($event)"></child>
</div>
`
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>
EDIT
Also, if you want a continuous effect, don't use #change - use #input instead:
Vue.component("Child", {
props: {
title: {
default: 'Just title'
}
},
data() {
return {
value: ''
}
},
template: `
<div class="child">
<h2>{{title}}</h2>
<input type="text" v-model="value" v-on:input="$emit('change', $event.target.value)">
</div>
`
})
new Vue({
el: "#app",
data() {
return {
title: 'Title from parent'
}
},
methods: {
processTitle(value) {
this.title = value.split("").reverse().join("");
}
},
template: `
<div class="parent">
<child :title="title" v-on:change="processTitle($event)"></child>
</div>
`
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>

Vue.js reactivity inner mechanisms

Given the following Vue code, how does it know to render the v-for again when selected is changed?
It makes complete sense to me when todos is changed.
So, Vue notices that there's a method isSelected involved and then uses "reflection" to watch the selected value, since it's an instance value?
Is that what's happening under the hood?
<div id="app">
<ol>
<li v-for="todo in todos" :class="{ 'selected': isSelected(todo.text) }">
{{ todo.text }}
</li>
</ol>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
todos: [
{ text: 'foo' },
{ text: 'bar' },
{ text: 'quz' }
],
'selected': 'bar'
},
methods: {
isSelected: function(text) {
return text != this.selected;
}
}
})
app.todos.push({ text: 'test' });
app.todos[0].text = 'change';
app.selected = 'foo';
</script>

Focus input of freshly added item

So I have a list of items and list of inputs linked to each item via v-for and v-model.
I click a button and add new item to that list. I want to focus input which is linked to newly added item.
Can't figure out how to achieve this goal.
<div id="app">
<div v-for="item in sortedItems">
<input v-model="item">
</div>
<button #click="addItem">
add
</button>
</div>
new Vue({
el: '#app',
data: {
items: []
},
methods: {
addItem: function() {
this.items.push(Math.random());
}
},
computed: {
sortedItems: function() {
return this.items.sort(function(i1, i2) {
return i1 - i2;
})
}
}
})
Here's fiddle with sorted list
https://jsfiddle.net/sfL91r95/1/
Thanks
Update: inspired by pkawiak's comment, a directive-based solution. I found that calling focus in the bind section didn't work; I had to use nextTick to delay it.
Vue.directive('focus-on-create', {
// Note: using Vue 1. In Vue 2, el would be a parameter
bind: function() {
Vue.nextTick(() => {
this.el.focus();
})
}
})
new Vue({
el: '#app',
data: {
items: []
},
methods: {
addItem: function() {
this.items.push(Math.random());
}
},
computed: {
sortedItems: function() {
return this.items.sort(function(i1, i2) {
return i1 - i2;
})
}
}
})
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<div id="app">
<div v-for="item in sortedItems">
<input v-focus-on-create v-model="item">
</div>
<button #click="addItem">
add
</button>
</div>
Original answer:
Make your input a component so that you can give it a ready hook.
const autofocus = Vue.extend({
template: '<input v-model="item" />',
props: ['item'],
ready: function() {
this.$el.focus();
}
})
new Vue({
el: '#app',
data: {
items: []
},
methods: {
addItem: function() {
this.items.push(Math.random());
}
},
components: {
autofocus
},
computed: {
sortedItems: function() {
return this.items.sort(function(i1, i2) {
return i1 - i2;
})
}
}
})
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<div id="app">
<div v-for="item in sortedItems">
<autofocus :item="item"></autofocus>
</div>
<button #click="addItem">
add
</button>
</div>
I Like to extend #Roy's answer.
if you are using any UI framework then it will create DIV and within the DIV input tag will be created so this Snippet will handle that case.
Vue.directive('focus-on-create', {
bind: function(el) {
Vue.nextTick(() => {
el.querySelector('input').focus()
})
}
})