Vue.js computed property loses its reactivity when passed through an event - javascript

I have a Modal component in my main app that gets passed content via an event whenever a modal has to be shown. Modal content is always a list with an action associated with each item, like "select" or "remove":
Vue.component('modal', {
data() {
return {
shown: false,
items: [],
callback: ()=>{}
}
},
mounted() {
EventBus.$on('showModal', this.show);
},
template: `<ul v-if="shown">
<li v-for="item in items">
{{ item }} <button #click="callback(item)">Remove</button>
</li>
</ul>`,
methods: {
show(items, callback) {
this.shown = true;
this.items = items;
this.callback = callback;
}
}
});
Sadly, when passing a computed property to that modal like in the component below, the reactive link gets broken -> if the action is "remove", the list is not updated.
Vue.component('comp', {
data() {
return {obj: {a: 'foo', b: 'bar'}}
},
computed: {
objKeys() {
return Object.keys(this.obj);
}
},
template: `<div>
<button #click="showModal">Show Modal</button>
<modal></modal>
</div>`,
methods: {
remove(name) {
this.$delete(this.obj, name);
},
showModal() {
EventBus.$emit('showModal', this.objKeys, this.remove);
}
}
});
See the minimal use case in this fiddle: https://jsfiddle.net/christophfriedrich/cm778wgj/14/
I think this is a bug - shouldn't Vue remember that objKeys is used for rendering in Modal and update it? (The forwarding of the change of obj to objKeys works.) If not, what am I getting wrong and how could I achieve my desired result?

You have the modal working with its own copy of items:
template: `<ul v-if="shown">
<li v-for="item in items">
{{ item }} <button #click="callback(item)">Remove</button>
</li>
</ul>`,
methods: {
show(items, callback) {
this.shown = true;
this.items = items;
this.callback = callback;
}
}
That copy is made once, upon the call to show, and what you are copying is just the value of the computed at the time you emit the showModal event. What show receives is not a computed, and what it assigns is not a computed. It's just a value.
If, anywhere in your code, you made an assignment like
someDataItem = someComputed;
the data item would not be a functional copy of the computed, it would be a snapshot of its value at the time of the assignment. This is why copying values around in Vue is a bad practice: they don't automatically stay in sync.
Instead of copying values around, you can pass a function that returns the value of interest; effectively a get function. For syntactic clarity, you can make a computed based on that function. Then your code becomes
const EventBus = new Vue();
Vue.component('comp', {
data() {
return {
obj: {
a: 'foo',
b: 'bar'
}
}
},
computed: {
objKeys() {
return Object.keys(this.obj);
}
},
template: `<div>
<div>Entire object: {{ obj }}</div>
<div>Just the keys: {{ objKeys }}</div>
<button #click="remove('a')">Remove a</button>
<button #click="remove('b')">Remove b</button>
<button #click="showModal">Show Modal</button>
<modal></modal>
</div>`,
methods: {
remove(name) {
this.$delete(this.obj, name);
},
showModal() {
EventBus.$emit('showModal', () => this.objKeys, this.remove);
}
}
});
Vue.component('modal', {
data() {
return {
shown: false,
getItems: null,
callback: () => {}
}
},
mounted() {
EventBus.$on('showModal', this.show);
},
template: `<div v-if="shown">
<ul v-if="items.length>0">
<li v-for="item in items">
{{ item }} <button #click="callback(item)">Remove</button>
</li>
</ul>
<em v-else>empty</em>
</div>`,
computed: {
items() {
return this.getItems && this.getItems();
}
},
methods: {
show(getItems, callback) {
this.shown = true;
this.getItems = getItems;
this.callback = callback;
}
}
});
var app = new Vue({
el: '#app'
})
<script src="//unpkg.com/vue#latest/dist/vue.js"></script>
<div id="app">
<comp></comp>
</div>

You are passing a value to a function, you are not passing a prop to a component. Props are reactive, but values are just values. You include modal in the template of comp, so rework it to take (at least) items as a prop. Then it will be reactive.
I would recommend having the remove process follow the emit-event-and-process-in-parent rather than passing a callback.
const EventBus = new Vue();
Vue.component('comp', {
data() {
return {
obj: {
a: 'foo',
b: 'bar'
}
}
},
computed: {
objKeys() {
return Object.keys(this.obj);
}
},
template: `<div>
<div>Entire object: {{ obj }}</div>
<div>Just the keys: {{ objKeys }}</div>
<button #click="remove('a')">Remove a</button>
<button #click="remove('b')">Remove b</button>
<button #click="showModal">Show Modal</button>
<modal :items="objKeys" event-name="remove" #remove="remove"></modal>
</div>`,
methods: {
remove(name) {
this.$delete(this.obj, name);
},
showModal() {
EventBus.$emit('showModal');
}
}
});
Vue.component('modal', {
props: ['items', 'eventName'],
data() {
return {
shown: false,
}
},
mounted() {
EventBus.$on('showModal', this.show);
},
template: `<div v-if="shown">
<ul v-if="items.length>0">
<li v-for="item in items">
{{ item }} <button #click="emitEvent(item)">Remove</button>
</li>
</ul>
<em v-else>empty</em>
</div>`,
methods: {
show(items, callback) {
this.shown = true;
},
emitEvent(item) {
this.$emit(this.eventName, item);
}
}
});
var app = new Vue({
el: '#app'
})
<script src="//unpkg.com/vue#latest/dist/vue.js"></script>
<div id="app">
<comp></comp>
</div>

Related

Remove an array from computed reverse method Vuejs

Good day, how to remove an array from a reverse method?
Here's my code
const app = Vue.createApp({
data() {
return {
app_title: 'Simple Checklist App',
entered_task_value: '',
list_of_tasks: [],
is_priority: false,
}
},
computed: {
reverseItems() {
return [...this.list_of_tasks].reverse();
}
},
methods: {
add_item() {
this.list_of_tasks.push(
{
id: this.list_of_tasks.length + 1,
data: this.entered_task_value,
priority: this.is_priority,
}
);
this.entered_task_value = '';
this.is_priority = '';
},
total_tasks() {
return this.list_of_tasks.length;
},
remove_item(task_index) {
return this.reverseItems.splice(task_index, 1);
}
},
});
app.mount('#app');
The remove_item method is not working and I am not sure how to properly call the property inside the computed
remove_item(task_index) {
return this.reverseItems.splice(task_index, 1);
}
This is the HTML
<ul>
<li
v-for="(task, task_index) in reverseItems"
class="item"
:key="task.id"
:class="{priority: task.priority}"
>
{{task.id}}
{{task.data}}
<button v-on:click="remove_item(task_index)">Remove</button>
</li>
</ul>
Thank you in Advance!
You should update the list_of_tasks of task array instead of the computed array.
The computed values are calculated from the real data and updated each time the data changes.
Here is the documentation about computed properties in vue.js
Here is a small example
new Vue({
el: '#app',
data: () => {
return {
myArr: [1,2,3,4,5]
}
},
computed: {
myArrReversed(){
return [...this.myArr].reverse()
}
},
methods : {
addItem(){
this.myArr.push(this.myArr.length +1)
},
removeItem(){
this.myArr.splice(this.myArr.length - 1, 1)
},
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<ul>
<li v-for="item of myArrReversed" :key='item'>
{{item }}
</li>
</ul>
<button #click="addItem">Add item</button>
<button #click="removeItem">Remove item</button>
</div>

Vue child component not re-rendering on data change

Trying to update a child component on parent state change. When I change the date state in Day.vue I can see that the computed function is working but the <EntryList> component is not updating with the new date I pass in.
Day.vue
<template>
<div id="daily">
<div id="nav">
<div class="nav">
<button #click="changeDay(-1)" class="arrow">←</button>
<h5 class="dayTitle" style="background-color: initial">
{{ dayTitle }}
</h5>
<button #click="changeDay(1)" class="arrow">→</button>
</div>
</div>
<div class="dayDiv">
<div class="details">
<!-- We use v-bind to attach state item to component--->
<EntryList v-bind:listDate="date" />
</div>
</div>
</div>
</template>
<script>
import EntryList from "./EntryList";
export default {
components: {
EntryList,
},
data() {
return {
date: "",
};
},
created() {
this.date = new Date();
},
methods: {
// Change Date here
changeDay(amount) {
let changeDate = new Date(this.date); // had to do this because computed couldn't see that it was updating
changeDate.setDate(this.date.getDate() + amount);
this.date = changeDate;
console.log("Date Changed");
},
},
computed: {
dayTitle() {
let options = { weekday: "short" };
return `${this.date.toLocaleString(
undefined,
options
)} ${this.date.toLocaleDateString()}`;
},
},
};
</script>
EntryList.vue
<template>
<div>
<ul>
<Entry v-for="entry in entries" v-bind:entry="entry" :key="entry.id" />
</ul>
<button :value="dateStamp" class="add">+</button>
</div>
</template>
<style lang="scss">
</style>
<script>
import Entry from "./Entry";
export default {
components: {
Entry,
},
// Eventually pass in props for styling component
props: {
listDate: {
type: Date,
required: true,
},
},
data() {
return {
entries: [],
};
},
created() {
// We do this to get the entries for the date
console.log("Render List");
let dateStamp = this.listDate.toLocaleDateString();
chrome.storage.sync.get([dateStamp], (result) => {
this.entries = Object.values(result[dateStamp]);
});
},
computed: {
dateStamp() {
return this.listDate.toLocaleDateString();
},
},
};
</script>
your entries array fills once on created event. You should move logic from created function, to computed property or use watcher
like this
watch: {
listDate (newValue) {
console.log("Render List");
let dateStamp = this.listDate.toLocaleDateString();
chrome.storage.sync.get([dateStamp], (result) => {
this.entries = Object.values(result[dateStamp]);
});
}
}

Vue state not updated with default injected value

If you click the button, you can see the value of state updated in the console, but it isn't updated in the page output. How can I make it work with a default injected value?
const Component = {
inject: {
state: {
default: () => ({
example: 1
})
}
},
template: `<div>
<div>{{ state }}</div>
<button #click="click">click</button>
</div>`,
methods: {
click() {
this.state.example += 1
console.log(this.state)
}
}
}
new Vue({
el: "#app",
components: {
Component
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<component></component>
</div>
Is it related to as Vue docs say "Note: the provide and inject bindings are NOT reactive. This is intentional. However, if you pass down an observed object, properties on that object do remain reactive."? I'm confused about the difference between the BINDINGS not being reactive but the OBSERVED OBJECT being reactive. Could you show an example to demo the difference?
Sorry, but it is not clear what you want - where's the provider for the "injection"? Why do you use inject in the same component as you use the value itself?
Here's your code, without inject:
1. Use the data attribute
const Component = {
data() {
return {
state: {
example: 1
}
}
},
template: `<div>
<div>{{ state }}</div>
<button #click="click">click</button>
</div>`,
methods: {
click() {
this.state.example += 1
console.log(this.state)
}
}
}
new Vue({
el: "#app",
components: {
Component
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<component></component>
</div>
Just use the data attribute - you can have a default value for example.
2. Use injection
inject is something completely different - it's a way to pass values from a provider to a consumer:
const Component = {
inject: ['state1'],
data() {
return {
state: {
example: 1
}
}
},
template: `<div>
<div>injected: {{ state1 }}</div>
<div>{{ state }}</div>
<button #click="click">click</button>
</div>`,
methods: {
click() {
this.state.example += 1
console.log(this.state)
}
}
}
new Vue({
el: "#app",
provide: {
state1: {
example1: 1
}
},
components: {
Component
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<component></component>
</div>
You can "skip" levels of components and use the provided value in components where you inject it - you don't have to pass it all the way down as props.
3. Create reactive inection
If you want to have reactive injection then you need to pass down something more complex:
const Component1 = {
inject: ['state2'],
data() {
return {
state: {
example: 1
}
}
},
template: `<div>
<div>injected: {{ state2.state2P }}</div>
<div>{{ state }}</div>
<button #click="click">click</button>
</div>`,
methods: {
click() {
this.state.example += 1
console.log(this.state)
}
}
}
new Vue({
el: "#app",
data() {
return {
state2: {
example2: 1
}
}
},
provide() {
// create an object (state2)
const state2 = {}
// define a property on the object (state2P), that
// has a get() function that always gets the provider's
// value you want to inject
Object.defineProperty(state2, 'state2P', {
enumerable: true,
get: () => this.state2,
})
// return the created object (with a property that always
// gets the value in the parent)
return {
state2
}
},
components: {
Component1
},
methods: {
parentClick() {
this.state2.example2 += 1
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<component1></component1>
<button #click="parentClick">PARENT CLICK</button>
</div>
I added a button to the template, so you can see that a method defined in the provider component's scope changes the value displayed in the consumer component's scope. (Also had to change the component's name, as Vue started to "whine" about using a restricted word.)

Vue.js pass function as prop and make child call it with data

I have a posts list component and a post component.
I pass a method to call from the posts list to the post component, so when a button is click it will be called.
But I want to pass the post id when this function is clicked
Code:
let PostsFeed = Vue.extend({
data: function () {
return {
posts: [....]
}
},
template: `
<div>
<post v-for="post in posts" :clicked="clicked" />
</div>
`,
methods: {
clicked: function(id) {
alert(id);
}
}
}
let Post = Vue.extend({
props: ['clicked'],
data: function () {
return {}
},
template: `
<div>
<button #click="clicked" />
</div>
`
}
as you can see in Post component you have a click that runs a method he got from a prop, I want to add a variable to that method.
How do you do that?
Normally, the click event handler will receive the event as its first argument, but you can use bind to tell the function what to use for its this and first argument(s):
:clicked="clicked.bind(null, post)
Updated answer: However, it might be more straightforward (and it is more Vue-standard) to have the child emit an event and have the parent handle it.
let Post = Vue.extend({
template: `
<div>
<button #click="clicked">Click me</button>
</div>
`,
methods: {
clicked() {
this.$emit('clicked');
}
}
});
let PostsFeed = Vue.extend({
data: function() {
return {
posts: [1, 2, 3]
}
},
template: `
<div>
<post v-for="post in posts" #clicked="clicked(post)" />
</div>
`,
methods: {
clicked(id) {
alert(id);
}
},
components: {
post: Post
}
});
new Vue({
el: 'body',
components: {
'post-feed': PostsFeed
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<post-feed></post-feed>
Using Vue 2 and expanding on #Roy J's code above, I created a method in the child component (Post) that calls the prop function and sends back a data object as part of the callback. I also passed in the post as a prop and used its ID value in the callback.
Back in the Posts component (parent), I modified the clicked function by referencing the event and getting the ID property that way.
Check out the working Fiddle here
And this is the code:
let Post = Vue.extend({
props: {
onClicked: Function,
post: Object
},
template: `
<div>
<button #click="clicked">Click me</button>
</div>
`,
methods: {
clicked() {
this.onClicked({
id: this.post.id
});
}
}
});
let PostsFeed = Vue.extend({
data: function() {
return {
posts: [
{id: 1, title: 'Roadtrip', content: 'Awesome content goes here'},
{id: 2, title: 'Cool post', content: 'Awesome content goes here'},
{id: 3, title: 'Motorcycle', content: 'Awesome content goes here'},
]
}
},
template: `
<div>
<post v-for="post in posts" :post="post" :onClicked="clicked" />
</div>
`,
methods: {
clicked(event) {
alert(event.id);
}
},
components: {
post: Post
}
});
new Vue({
el: '#app',
components: {
'post-feed': PostsFeed
}
});
And this is the HTML
<div id="app">
<post-feed></post-feed>
</div>
this is the service:
export const getBuilding = () => {
console.log("service");
return 0;
};
in the parent component:
<Update-Theme :method="parentMethod"/>
import { getBuilding } from "./service";
methods: {
parentMethod() {
console.log("Parent");
getBuilding();
},
}
and in the child component
<v-btn color="green darken-1" text #click="closeDialog()">
props: [ "method"],
methods: {
closeDialog() {
this.method();
//this.$emit("update:dialog", false);
},
}

Can't get method to execute on parent component from child component

I'm trying to get a method to execute on a parent component when a button in one of its child components is clicked. I am using single file components with Webpack. Here's the code for the child component:
<template>
<button v-on:click="add">Click</button>
</template>
<script>
export default {
methods: {
add: () => {
console.log('foo')
this.$dispatch('addClick')
}
}
}
</script>
And the code for the parent:
<template>
<div id="app">
<count :total="total"></count>
<click></click>
</div>
</template>
<script>
import count from './components/count.vue'
import click from './components/click.vue'
export default {
components: {
count,
click
},
data: () => {
return {
total: 0
}
},
methods: {
addToTotal: () => {
console.log('bar')
this.total += 1
}
},
events: {
addClick: 'addToTotal'
}
}
</script>
The count component is just an h1 element that displays the total variable. When I click the button, "foo" logs to the console, but "bar" does not and the total doesn't change. Any ideas on what I'm doing wrong? Thanks in advance!
You are using lambda notation for your methods, which is giving them the wrong this. If you use function instead, it will work.
Vue.component('click', {
template: '#clicker',
methods: {
add: function() {
console.log('foo')
this.$dispatch('addClick')
}
}
})
new Vue({
el: '#app',
data: () => {
return {
total: 0
}
},
methods: {
addToTotal: function () {
console.log('bar')
this.total += 1
}
},
events: {
addClick: 'addToTotal'
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<template id="clicker">
<button v-on:click="add">Click</button>
</template>
<div id="app">
<count :total="total"></count>
<click></click>
{{total}}
</div>
Use two-way .sync binding type modifier on total property of count component so that the value will be updated when parent total value is changed. Here is an example:
Vue.component('click', {
template: '<button v-on:click="add">Click</button>',
methods: {
add: function () {
this.$dispatch('addClick');
}
}
});
Vue.component('count', {
template: '<h1 v-text="total"></h1>',
props: {
total: {
type: Number,
twoWay: true
}
}
});
new Vue({
el: '#app',
data: {
total: 1
},
methods: {
addTotal: function () {
this.total++;
}
},
events: {
addClick: 'addTotal'
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.25/vue.min.js"></script>
<div id="app">
<count :total.sync="total"></count>
<click></click>
</div>

Categories

Resources