Make computed Vue properties dependent on current time? - vue.js

I have a collection of Events. These will render in lists according to their status - upcoming/live/previous. Thus the rendering is dependent on the current time. How can I make the computed properties to update/recompute as time goes by?
<template>
<div>
<h2>Upcoming events</h2>
<p v-bind:key="event.name" v-for="event in upcomingEvents">{{ event.name }}</p>
<h2>Live events</h2>
<p v-bind:key="event.name" v-for="event in liveEvents">{{ event.name }}</p>
<h2>Previous events</h2>
<p v-bind:key="event.name" v-for="event in previousEvents">{{ event.name }}</p>
</div>
</template>
<script>
import Event from '../Event.js'
export default {
data() {
return {
events: []
}
},
computed: {
upcomingEvents() {
return this.events.filter(event => event.isUpcoming())
},
liveEvents() {
return this.events.filter(event => event.isLive())
},
previousEvents() {
return this.events.filter(event => event.isPrevious())
},
},
mounted() {
// this.events are populated here
}
}
</script>

You can declare a time-dependent data variable and use setInterval() to update it:
data() {
return {
events: [],
now: Date.now()
}
},
created() {
var self = this
setInterval(function () {
self.now = Date.now()
}, 1000)
},
computed: {
upcomingEvents() {
return this.events.filter(event => event.isUpcoming(this.now))
},
liveEvents() {
return this.events.filter(event => event.isLive(this.now))
},
previousEvents() {
return this.events.filter(event => event.isPrevious(this.now))
}
}
Note that you need to use now in computed properties to make them update.

One possibility for your case is $forceUpdate(). However, it should be note that it will work specifically for your case because you're NOT using child components.
If you were to use child components, you would then need to use slots within the parent component and insert the children within their respective slots.
So, for example, you could do:
created() {
setInterval(() => {
this.$forceUpdate()
}, 5000)
}
Which will cause the entire component to re-render. This may or may not be the desirable interaction you're looking for.

You could create a time variable that you update every second then use this variable in your computed properties.
new Vue({
el: "#app",
data: {
time: ''
},
computed: {
computedValue: function(){
return this.time;
}
},
mounted: function(){
var app = this;
setInterval(function(){
app.time = parseInt(new Date().getTime() / 1000);
}, 1000);
}
})
https://jsfiddle.net/ecwnvudz/

Related

How pass object, contains computed property, to child?

<template>
child-component(
v-for="item in items"
:item="item"
)
</template>
<script>
data() {
return {
items: [],
valueFromApi: null,
}
},
computed: {
someCompProp() { return val // math based on valueFromApi }
},
created: {
setInterval(() => { // make api call and set valueFromApi }, 2000)
this.createItems();
},
methods: {
createItems() {
// ...someActions
formedItems.forEach((item) => {
this.items.push({
...item,
someValue: this.someCompProp,
})
})
this.items.push(item)
},
apiCall() {
// store result to valueFromApi
}
</script>
Now it's not reactive.
I can achive reactivity only passing computed prop like independed property.
Can computed property someCompProp be reactive in child prop item obj?
Okay, its done, i just return computed prop in someValue. someValue: () => this.someCompProp,

listen to events from dynamic vue components

How would you listen to an event emitted by a dynamically created component instance?
In the example, the top component is added in the DOM, while the second is dynamically created in javascript.
Vue.component("button-counter", {
data: function() {
return {
count: this.initial_count
}
},
props: ['initial_count'],
methods: {
add: function() {
this.count++
this.$emit('myevent', this.count)
}
},
template: '<button v-on:click="add">You clicked me {{ count }} times.</button>'
})
let app = new Vue({
el: "#app",
data() {
return {
initial_count: 10,
}
},
mounted: function() {
let initial_count = this.initial_count
let ButtonCounterComponentClass = Vue.extend({
data: function() {
return {}
},
render(h) {
return h("button-counter", {
props: {
initial_count: initial_count
}
})
}
})
let button_counter_instance = new ButtonCounterComponentClass()
button_counter_instance.$mount()
button_counter_instance.$on('myevent', function(count) {
console.log('listened!')
this.say(count)
})
this.$refs.container.appendChild(button_counter_instance.$el)
},
methods: {
say: function(message) {
alert(message)
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue#2.6.10/dist/vue.js"></script>
<div id="app">
<button-counter initial_count=20 v-on:myevent="say"></button-counter>
<div ref='container'></div>
</div>
If I've understood what you want then you just need to listen for the event on the inner component and pass it on.
I've used arrow functions in a couple of places to avoid problems with this bindings. Otherwise I've tried to leave your code unchanged as much as possible. Changes marked with ****.
Vue.component("button-counter", {
data: function() {
return {
count: this.initial_count
}
},
props: ['initial_count'],
methods: {
add: function() {
this.count++
this.$emit('myevent', this.count)
}
},
template: '<button v-on:click="add">You clicked me {{ count }} times.</button>'
})
let app = new Vue({
el: "#app",
data() {
return {
initial_count: 10,
}
},
mounted: function() {
let initial_count = this.initial_count
let ButtonCounterComponentClass = Vue.extend({
data: function() {
return {}
},
render(h) {
return h("button-counter", {
props: {
initial_count: initial_count
},
// **** Added this ****
on: {
myevent: count => {
this.$emit('myevent', count);
}
}
// ****
})
}
})
let button_counter_instance = new ButtonCounterComponentClass()
button_counter_instance.$mount()
// **** Changed the next line ****
button_counter_instance.$on('myevent', count => {
console.log('listened!')
this.say(count)
})
this.$refs.container.appendChild(button_counter_instance.$el)
},
methods: {
say: function(message) {
alert(message)
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue#2.6.10/dist/vue.js"></script>
<div id="app">
<button-counter initial_count=20 v-on:myevent="say"></button-counter>
<div ref='container'></div>
</div>
It's important to understand that button_counter_instance is not an instance of your button-counter component. You've wrapped it in another component, albeit a component that doesn't add any extra DOM nodes. So listening on the wrapper component is not the same as listening on button-counter.
Docs for what you can pass to h: https://v2.vuejs.org/v2/guide/render-function.html#The-Data-Object-In-Depth

unable to access array objects

I am trying to access into an array from computed. console vuex showed computed array is there, but I cannot access into the array from created(). Any help is appreciated!
I have tried to save into a data array, does not find the computed array.
<template>
<div>
{{ product.product_name }}
</div>
</template>
<script>
export default {
name: 'product_4',
created() {
this.product = this.products.find((product) => product.id == 4);
},
data() {
return {
product: {}
}
},
computed: {
products() {
return this.$store.getters.products;
}
}
}
</script>
store.js
state: {
products:[]
},
getters: {
products(state) {
return state.products;
}
},
mutations: {
updateGetProducts(state, payload) {
state.products = payload;
}
},
actions: {
getProducts(context) {
axios.get('/api/getproducts')
.then((response)=> {
context.commit('updateGetProducts', response.data);
});
}
}
computed properties are mounted after the created life cycle hook, so try to use another hook like mounted :
mounted(){
this.product = this.products.find((product) => product.id == 4);
}
I think should not make any problem, if you use like below, but you have to ensure that find method returning a single object instead of null or array of objects.
created() {
this.product = this.$store.getters.products.find((product) => product.id == 4);
}
but I ll prefer to use that into mounted hook like below when you want to use computed property.
mounted() {
this.product = this.products.find((product) => product.id == 4);
}
And after looking your updated code you can use below solution, because I have seen that you have used actions to update products using api, so below solution will solve your problem
<template>
<div>
{{ product.product_name }}
</div>
</template>
<script>
export default {
name: 'product_4',
data() {
return {
}
},
computed: {
product() {
return this.$store.getters.products.find((p) => p.id == 4);
}
}
}
</script>
I changed the computed to this:
computed: {
product() {
return this.$store.getters.products.find((product) => product.id == 4);
}
}
I can access directly this way, do not need to put into data as it is not advised to do so in vue documentation.

Updating a prop inside a child component so it updates on the parent container too

So I have a simple template like so:
<resume-index>
<div v-for="resume in resumes">
<resume-update inline-template :resume.sync="resume" v-cloak>
//...my forms etc
<resume-update>
</div>
<resume-index>
Now, inside the resume-updatecomponent I am trying to update the prop on the inside so on the outside it doesn't get overwritten, my code is like so;
import Multiselect from "vue-multiselect";
import __ from 'lodash';
export default {
name: 'resume-update',
props: ['resume'],
components: {
Multiselect
},
data: () => ({
form: {
name: '',
level: '',
salary: '',
experience: '',
education: [],
employment: []
},
submitted: {
form: false,
destroy: false,
restore: false
},
errors: []
}),
methods: {
update(e) {
this.submitted.form = true;
axios.put(e.target.action, this.form).then(response => {
this.resume = response.data.data
this.submitted.form = false;
}).catch(error => {
if (error.response) {
this.errors = error.response.data.errors;
}
this.submitted.form = false;
});
},
destroy() {
this.submitted.destroy = true;
axios.delete(this.resume.routes.destroy).then(response => {
this.resume = response.data.data;
this.submitted.destroy = false;
}).catch(error => {
this.submitted.destroy = false;
})
},
restore() {
this.submitted.restore = true;
axios.post(this.resume.routes.restore).then(response => {
this.resume = response.data.data;
this.submitted.restore = false;
}).catch(error => {
this.submitted.restore = false;
})
},
reset() {
for (const prop of Object.getOwnPropertyNames(this.form)) {
delete this.form[prop];
}
}
},
watch: {
resume: function() {
this.form = this.resume;
},
},
created() {
this.form = __.cloneDeep(this.resume);
}
}
When I submit the form and update the this.resume I get the following:
[Vue warn]: Avoid mutating a prop directly since the value will be
overwritten whenever the parent component re-renders. Instead, use a
data or computed property based on the prop's value. Prop being
mutated: "resume"
I have tried adding computed to my file, but that didn't seem to work:
computed: {
resume: function() {
return this.resume
}
}
So, how can I go about updating the prop?
One solution:
simulate v-model
As Vue Guide said:
v-model is essentially syntax sugar for updating data on user input
events, plus special care for some edge cases.
The syntax sugar will be like:
the directive=v-model will bind value, then listen input event to make change like v-bind:value="val" v-on:input="val = $event.target.value"
So the steps:
create one prop = value which you'd like to sync to parent component
inside the child component, create one data porperty=internalValue, then uses Watcher to sync latest prop=value to data property=intervalValue
if intervalValue change, emit one input event to notice parent component
Below is one simple demo:
Vue.config.productionTip = false
Vue.component('container', {
template: `<div>
<p><button #click="changeData()">{{value}}</button></p>
</div>`,
data() {
return {
internalValue: ''
}
},
props: ['value'],
mounted: function () {
this.internalValue = this.value
},
watch: {
value: function (newVal) {
this.internalValue = newVal
}
},
methods: {
changeData: function () {
this.internalValue += '#'
this.$emit('input', this.internalValue)
}
}
})
new Vue({
el: '#app',
data () {
return {
items: ['a', 'b', 'c']
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<div>
<p>{{items}}
<container v-for="(item, index) in items" :key="index" v-model="items[index]">
</container>
</div>
</div>
or use other prop name instead of value (below demo use prop name=item):
Also you can use other event name instead of event name=input.
other steps are similar, but you have to $on the event then implement you own handler like below demo.
Vue.config.productionTip = false
Vue.component('container', {
template: `<div>
<p><button #click="changeData()">{{item}}</button></p>
</div>`,
data() {
return {
internalValue: ''
}
},
props: ['item'],
mounted: function () {
this.internalValue = this.item
},
watch: {
item: function (newVal) {
this.internalValue = newVal
}
},
methods: {
changeData: function () {
this.internalValue += '#'
this.$emit('input', this.internalValue)
this.$emit('test-input', this.internalValue)
}
}
})
new Vue({
el: '#app',
data () {
return {
items: ['a', 'b', 'c']
}
},
methods: {
syncChanged: function (target, index, newData) {
this.$set(target, index, newData)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<div>
Event Name=input
<p>{{items}}</p>
<container v-for="(item, index) in items" :key="index" :item="item" #input="syncChanged(items, index,$event)">
</container>
</div>
<hr> Event Name=test-input
<container v-for="(item, index) in items" :key="index" :item="item" #test-input="syncChanged(items, index,$event)">
</container>
</div>
I usually use vuex to manage variables that I will be using in multiple components and like the error says, load them in the various components using the computed properties. Then use the mutations property of the store object to handle changes
In component files
computed: {
newProfile: {
get() {
return this.$store.state.newProfile;
},
set(value) {
this.$store.commit('updateNewProfile', value);
}
},
In the vuex store
state: {
newProfile: {
Name: '',
Website: '',
LoginId: -1,
AccountId: ''
}
},
mutations: {
updateNewProfile(state, profile) {
state.newProfile = profile;
}
}

VueJs Nested props coming through undefined

I am trying to access an array which is part of a prop (event) passed into a component, but when in created() or mounted() the array part of the event prop (the rest is fine) comes through as undefined.
As can be seen below, when I inspect the props in the vue chrome plugin, the registration_fields are there.
I can add a watcher to the event prop and can access the registration_fields that way, but this seems very awkward to have to do this to access already passed in data.
This is from the Chrome vue inspector:
event:Object
address1_field:"Some Address 1"
address2_field:"Some Address 2"
approved:true
registration_fields:Array[1]
This is what part of my vue file looks like:
export default {
props: ['event'],
data() {
return {
regFields: []
}
},
created() {
this.regFields = this.event.registration_fields // Undefined here!
},
watch: {
event() {
this.regFields = this.event.registration_fields //Can access it here
});
}
}
}
I am using Vue 2.4.4
This is how the component is called:
<template>
<tickets v-if="event" :event="event"></tickets>
</template>
<script>
import tickets from './main_booking/tickets.vue'
export default {
created() {
var self = this;
this.$http.get('events/123').then(response => {
self.event = response.data
}).catch(e => {
alert('Error here!');
})
},
data: function () {
return {event: {}}
},
components: {
tickets: tickets
}
}
</script>
Thank you
It actually works fine without the watcher.
new Vue({
el: '#app',
data: {
event: undefined
},
components: {
subC: {
props: ['event'],
data() {
return {
regFields: []
}
},
created() {
this.regFields = this.event.registration_fields // Undefined here!
}
}
},
mounted() {
setTimeout(() => {
this.event = {
registration_fields: [1, 3]
};
}, 800);
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
<sub-c v-if="event" :event="event" inline-template>
<div>
{{regFields}}
</div>
</sub-c>
</div>
If, as Belmin Bedak suggests in the comment below, event is populated asynchronously, it comes in as undefined because it's undefined. In that case, you need a watcher, or, somewhat more elegantly, use a computed:
new Vue({
el: '#app',
data: {
event: {}
},
components: {
subC: {
props: ['event'],
computed: {
regFields() {
return this.event.registration_fields;
}
}
}
},
// delay proper population
mounted() {
setTimeout(() => { this.event = {registration_fields: [1,2,3]}; }, 800);
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
<sub-c :event="event" inline-template>
<div>
{{regFields}}
</div>
</sub-c>
</div>