link2329 link2330 link2331 link2332 link2333 link2334 link2335 link2336 link2337 link2338 link2339 link2340 link2341 link2342 link2343 link2344 link2345 link2346 link2347 link2348 link2349 link2350 link2351 link2352 link2353 link2354 link2355 link2356 link2357 link2358 link2359 link2360 link2361 link2362 link2363 link2364 link2365 link2366 link2367 link2368 link2369 link2370 link2371 link2372 link2373 link2374 link2375 link2376 link2377 link2378 link2379 link2380 link2381 link2382 link2383 link2384 link2385 link2386 link2387 link2388 link2389 link2390 link2391 link2392 link2393 link2394 link2395 link2396 link2397 link2398 link2399 link2400 link2401 link2402 link2403 link2404 link2405 link2406 link2407 link2408 link2409 link2410 link2411 link2412 link2413 link2414 link2415 link2416 link2417 link2418 link2419 link2420 link2421 link2422 link2423 link2424 link2425 link2426 link2427 link2428 link2429 link2430 link2431 link2432 link2433 link2434 link2435 link2436 link2437 link2438 link2439 link2440 link2441 link2442 link2443 link2444 link2445 link2446 link2447 link2448 link2449 link2450 link2451 link2452 link2453 link2454 link2455 link2456 link2457 link2458 link2459 link2460 link2461 link2462 link2463 link2464 link2465

[Vue.js] Printing an iframe to a PDF - how to get content from the page using VueJS

when trying to print a dashboard from my app. The dashboard has embedded iFrame graphs and to include them on the PDF.

when using JSPDF. when able to generate a PDF of text elements so the plugin is working correctly.

My question is how do I get the content from the iFrame. Here’s where when so far:

In my html file:

<iframe class=”myiframe” v-bind:src=”iframe_url”></iframe>

and my vuejs script:

import jsPDF from ‘jspdf’
export default {
methods: {
downloadPDF() {
const doc = new jsPDF();
// some code…
// iFrames
vOffset + 10
doc.text(25, vOffset, ‘Data Flows’)
var iFrameBody = document.getElementById(‘myiframe’)
doc.fromHTML(iFrameBody, 15, vOffset)
doc.save(“sample.pdf”)
}

}

}

The PDF prints correctly but is blank where the iFrame should appear.

I’ve searched the github repo for jsPDF and also stackoverflow for solutions but haven’t found anything that works.

Any tips would be great.

Solution :

Looks like I was running into two issues.

Firstly, I wasn’t getting the content from the iFrame correctly. Changing this line

var iFrameBody = document.getElementById(‘myiframe’)

to this

var iFrameBody = this.$refs.myiframe.contentWindow.document

..gave me access to the iframe document.

However, as explained very well in this solution, I ran into a same-origin-policy issue. This is what @hammerbot referred in his comment.

[Vue.js] Refresh details page from child component

there is a details page where i display product details and photos of relateds products
I would pass data from a child component to the parent that is the details page.

This is my product page

<template>
<div class=”page” :newProduct=”newProduct”
@updateDetailsPage=”updatePage” >
<product-details v-if=”product” :product=”product” />
<correlateds v-if=”correlateds” :correlateds=”correlateds” />
</div>
</template>

<script>
import axios from “axios”;
import ProductDetails from “../components/product/Details.vue”;
import Correlateds from “../components/product/Correlateds.vue”;
export default {
name: “product”,
components: {
ProductDetails,
Correlateds
},
data() {
return {
product: null,
correlateds:null,
newProduct:null
};
},
methods: {
setData(product, correlateds) {
this.product = product;
this.correlateds = correlateds;
},
updatePage(newProduct){
alert(‘new’);
//this.newProduct = newProduct;
//console.log(‘new product’, newProduct);
}
},
beforeRouteEnter(to, from, next) {
axios
.all([
axios.get(`/api/products/details/${to.params.codart}`),
axios.get(`/api/products/correlated/${to.params.codart}`)
])
.then(
axios.spread((product, correlateds) => {
next(vm =>{
vm.setData(product.data, correlateds.data);
// console.log(products.data);
}
);
})
);
}
};
</script>

This is my correlated components

<template>
<div class=”container pt-4 pb-1 pl-2 pr-1”>
<h3 class=”text-center”><i>You may also like…</i></h3>
<div class=”row”>
<div v-for=”(related, i) in correlateds” :key=”i” class=”col-
md-4 pt-1 pb-1 pr-1 pl-1”>
<img
:src=”`../../assets/foto/${related.fotoBig}`“
:alt=”related.ranCodart”
class=”img-fluid img-thumbnail rounded-circle”
@click=”refreshDetails(related.codart)”
\>
</div>
</div>
</div>
</template>

<script>
import axios from “axios”;
export default {
name: “correlateds”,
data(){
return{
newProduct:{
article:{},
relateds:[]
}
}
},
props: {
correlateds: {
type: Array
}
},
methods:{
refreshDetails(codart)
{
this.$router.push(`/products/details/${codart}`);
//window.location.reload();//refresh page ***

axios
.all([
axios.get(`/api/products/details/${codart}`),
axios.get(`/api/products/correlated/${codart}`)
])
.then(
axios.spread((product, correlateds) => {
this.newProduct.article = product.data;
this.newProduct.relateds = correlateds.data;
console.log(this.newProduct);
}))
.then(() => this.$emit(‘updateDetailsPage’, this.newProduct))
.catch(error => console.log(error.response));
}
}

};
</script>

When i click on a image i see in the console the newProduct is right
but in the parent nothing happen: i try to run an alert to see something but nothing happens

Solution :

Note the event updateDetailsPage is emitted by correlateds component so you should get in this component, not in the div. See:

<correlateds v-if=”correlateds” :correlateds=”correlateds” @updateDetailsPage=”updatePage” />

[Vue.js] Math.round() as v-model return value

there is an issue with Math.round() used with v-model in the following template:

<v-text-field v-model=”rounded” />

rounded is a computed property:

rounded: {
get() {
return this.value;
},
set (val) {
this.value = Math.round(val);
console.log(this.value);
}
}

Expected results seen in v-text-field:

Input | Expected Value | Actual Value
\===============================================
1.12 | 1 | 1.12
1.6 | 2 | 2

Why doesn’t the v-text-field show 1 when I enter 1.12?

Solution :

Rather than bind to a computed property, watch the value and update it.

<v-text-field v-model=”rounded” />

{
data() {
return {
rounded: 0
}
},

watch: {
rounded(val) {
let newVal = Math.round(val);
if (newVal !== val) {
this.val = newVal
}
// or even simply this.val = Math.round(this.val) without the check …
}
}
}

Solution 2:

The main cause is, you are changing the value not rounded variable, so if you do like below , hope the problem will solved.

<v-text-field v-model=”rounded” :value=”val” @change=”OnChange” />

and add val property into data block:

data(){
return:{
val:0.00
}
}

No need to do anything for computed property, just write the OnChange method into methods block like below:

methods:{
OnChange(newVal){
this.val = Math.round(newVal);
this. rounded=this.val;
}
}

[Vue.js] Vue offsetTop always returns 0

I’m trying to make an element fixed when the user scrolls past it, but there is an issue. For some reason my element (in my case it’s a navbar) always returns 0 despite being at like 300px height more or less.

This is my mounted method where I do the calculation, as you see I’m console loging stickyTop, always 0.

I tried with offsetTop and getBoundingClientRect().top and both return 0 always.

mounted() {
console.log(this.$options.name+’ component successfully mounted’);
let self = this;
let sticky = document.getElementById(“sticky”);
//sticky.style.border = ‘10px solid red’;
//let stickyTop = sticky.getBoundingClientRect().top;
let stickyTop = sticky.offsetTop;
console.log(stickyTop);
let scrolled = false;
let $window = window;

window.addEventListener(‘scroll’, function(e) {
scrolled = true;
});

let timeout = setInterval(function() {
/* If the page was scrolled, handle the scroll */
if (scrolled) {
scrolled = false;
if (window.pageYOffset > stickyTop) {
self.isScrolled = true;
}
else {
self.isScrolled = false;
}
}
}, 2000);
},

My full component just in case:

<nav id=”sticky” class=”LAYOUTnav1_maincontainer” :class=”{ ‘fixed_class’ : isScrolled }” @mouseleave=”activeNav = null”>
<div class=”LAYOUTnav1_links_container”>
<a class=”LAYOUTnav1_link_container hover_slide_center” v-for=”(link, index) in visibleLinks” :key=”index” @mouseover=”selectNav(link, $event);” @click=”selectNav(link, $event);” :href=”link.url” :class=”{ active_nav : meta.activeNav == link.name}”>
<span class=”LAYOUTnav1_link_text”>{ link.name }</span>
</a>
<button class=”LAYOUTnav1_cart_button” type=”button” @click=”TOGGLE_CART_TAB()” v-bg-color=”‘rgb(10,10,10)’”>
<i class=”LAYOUTnav1_cart_button_icon fas fa-shopping-cart”></i>
<span class=”LAYOUTnav1_cart_button_text” v-if=”cartItems.length != 0”>{ cartItems.length }</span>
<span class=”LAYOUTnav1_cart_button_text” v-if=”cartItems.length == 0”>El carrito esta vacio!</span>
</button>
</div>
<div class=”LAYOUTnav1_responsive_container”>
<a class=”LAYOUTnav1_responsive_title” href=”/“>{ globals.generals.appName }</a>
<button class=”LAYOUTnav1_responsive_button” @click.self=”selectNav({ name: ‘responsive’, sublinks: []}, $event)”>
<i class=”LAYOUTnav1_responsive_button_icon fas fa-bars” v-show=”!showResponsiveNav”></i>
<i class=”LAYOUTnav1_responsive_button_icon fas fa-times” v-show=”showResponsiveNav”></i>
</button>
</div>
<div class=”LAYOUTnav1_dropdowns_container” v-show=”activeNav == ‘responsive’”>
<a class=”LAYOUTnav1_dropdown_container” v-for=”link in visibleLinks” :key=”link.name” @mouseover=”selectNav(link, $event);” @click=”selectNav(link, $event);” :href=”link.url” :class=”{ active_nav : meta.activeNav == link.name}”>
<span class=”LAYOUTnav1_dropdown_text”>{ link.name }</span>
</a>
</div>
</nav>
</template>
<!–SCRIPTS–>
<script>
import $ from ‘jquery’;
import { mapState, mapGetters, mapActions, mapMutations } from ‘vuex’;
export default {
name: ‘LAYOUTnav6’,

computed: {

…mapState(‘Cart’, [‘cartItems’]),

withLinks: function(){
return this.globals.navLinks.filter(link => link.sublinks.length > 0 && link.subLinks);
},

visibleLinks: function(){
return this.globals.navLinks.filter(link => link.isVisible && !link.hasSublinks || link.isVisible && link.hasSublinks && link.sublinks.length > 0);
}
},

data: function () {
return {
activeNav: null,
showResponsiveNav: false,
isScrolled: false,
}
},

props: {
globals: {required:true},
meta: {required:true}
},

mounted() {
console.log(this.$options.name+’ component successfully mounted’);
let self = this;
let sticky = document.getElementById(“sticky”);
//sticky.style.border = ‘10px solid red’;
//let stickyTop = sticky.getBoundingClientRect().top;
let stickyTop = sticky.offsetTop;
console.log(stickyTop);
let scrolled = false;
let $window = window;

window.addEventListener(‘scroll’, function(e) {
scrolled = true;
});

let timeout = setInterval(function() {
/* If the page was scrolled, handle the scroll */
if (scrolled) {
scrolled = false;
if (window.pageYOffset > stickyTop) {
self.isScrolled = true;
}
else {
self.isScrolled = false;
}
}
}, 2000);
},

methods: {

…mapMutations(‘Cart’, [‘TOGGLE_CART_TAB’]),

selectNav: function(link, event){
if(link.sublinks.length > 0){
//event.preventDefault();
this.activeNav = link.name;
}
else{
this.activeNav = link.name;
this.showResponsiveNav = !this.showResponsiveNav
}
},

}

};
</script>

Solution :

You most likely have another element (a child of window, body, etc) with the overflow property set to auto or scroll. That is the element you need to get offsetTop from.

Use development tools to locate the element that owns the scroll bar, and then use a reference to that element instead of window.

[Vue.js] VueJS/VueX display table when store state has been populated

I’m trying to develop a single file component where i would like to fetch user cars from backend and display the all loaded cars in a table.

What is the best way to handle that ?

For the moment, i call a store action (getUserCars) from the created() hook, and then I try to listen any change on a state property of my store using a watch to be able to build my table in UI. But it doesn’t work yet..

Could you please help me?

<script>
import { mapActions, mapGetters } from “vuex”;

export default {
created: function() {
console.log(“created() - called”);
this.getUserCars();
},
mounted: function() {
console.log(“mounted() - called”);
},
destroyed: function() {
console.log(“destroyed() - called”);
},
watch: {
userSites(newValue, oldValue) {
console.log(`watch() Updating from ${oldValue} to ${newValue}`);

const options = {
data: {type: “local”, source: this.userCars(), pageSize: 5},
layout: {theme: “default”, class: “”, scroll: !1, footer: !1},
sortable: !0,
pagination: !0,
columns: [
{field: “name”, title: “Name”},
{field: “createdAt”, title: “Created At”}
]
};
$(‘#m_datatable’).mDatatable(options);

},
},
computed: {

},
methods: {
…mapGetters([“userCars”]),
…mapActions([“getUserCars”]),
}
};
</script>

Solution :

If the getUserCars() action in the store hydrates the state with the data, then you can have a getter like the userCars one I can see in the code. You just have to move the mapGetters helper from methods to computed.

Then you can access it in the template and do whatever you want.

computed: {
…mapGetters([“userCars”])
},
methods: {
…mapActions([“getUserCars”])
}

[Vue.js] how to get start with express and nuxt/viue for this default setting

hello to ask about how to get start using express and vue.js because the documentation of nuxt different, and when using the default setting on nuxt js,
the default set on server.js something like this

const express = require(‘express’)
const consola = require(‘consola’)
const { Nuxt, Builder } = require(‘nuxt’)
const app = express()

// Import and Set Nuxt.js options
let config = require(‘../nuxt.config.js’)
config.dev = !(process.env.NODE_ENV === ‘production’)

async function start() {
// Init Nuxt.js
const nuxt = new Nuxt(config)

const { host, port } = nuxt.options.server

// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
} else {
await nuxt.ready()
}

app.get(‘/route’, (req, res) => { // i test this, but failed
res.json({ message: ‘yes’ }) // then on .vue.js feel i use axios to get this localhost
})

// Give nuxt middleware to express
app.use(nuxt.render)

// Listen the server
app.listen(port, host)
consola.ready({
message: `Server listening on http://${host}:${port}`,
badge: true
})
}
start()

should i create the some router inside the start function ? and how to export them in nuxt and get the data in the .vue.js file? when still new here
can anyone give me very simple example for this, :D

Solution :

you have 2 options put togheter express and Nuxt, making live express in the server directory or use nuxt pure as frontend (awesomesite.com) and express pure as api (api.awesomesite.com), in any of the two cases the life is more easy if you use axios and configure them in the nuxt.config.js file,

axios: {
baseURL: process.env.AXIOS_SERVER
// See https://github.com/nuxt-community/axios-module#options
},

after that you use axios as usual in the components to communicate with the server side.

I thing you try to use express embed with nuxt. To do that i prefers create a structure inside server directory

/server
/router
index.js
index.js
globals.js

router/index.js

const router = require(‘express’).Router()

router.post(‘/your-route’, function (req, res, next) {
//todo this route
});
router.post(‘/other-route’, function (req, res, next) {
//todo this route
});
module.exports.router = router;

server/index.js

const express = require(‘express’)
const consola = require(‘consola’)
const { Nuxt, Builder } = require(‘nuxt’)
const app = express()
{ router } = require(‘./router’) //the router!!!

// Import and Set Nuxt.js options
let config = require(‘../nuxt.config.js’)
config.dev = !(process.env.NODE_ENV === ‘production’)
app.use(‘/‘, router) // ‘/‘ or ‘/api’ depends to you

async function start() {
// Init Nuxt.js
const nuxt = new Nuxt(config)

const { host, port } = nuxt.options.server

// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
} else {
await nuxt.ready()
}

// Give nuxt middleware to express
app.use(nuxt.render)

// Listen the server
app.listen(port, host)
consola.ready({
message: `Server listening on http://${host}:${port}`,
badge: true
})
}
start()

in a vue.js component you can use AXIOS simply like that:

methods: {
async send() {
this.waiting = true
await this.$axios({
method: ‘post’,
url: ‘/your-route’,
data: this.form
})
.then(res => {
this.success = true
this.error = false
this.onReset()
})
.catch(e => {
this.error = true
this.success = false
})
this.waiting = false
}
}

[Vue.js] Multi selected Filter in Vue.js

there is a selection of checkbox groups (hotel type and locations) and to filter the results based on what has been selected. How can I add my selectedLocations and types to the filteredHotels() method and get a filtered result. Sydney Hotels, Sydney Backpackers, Sydney or Melbourne hotels or all Hotels if only hotels is selected.

HTML

<div>
<div class=”row pt-5”>
<div class=”col”>
<h5>Locations</h5>
<label v-for=”(value, key) in locations”>
{value}
<input type=”checkbox” :value=”value” v-model=”selectedLocations”>
</label>
{selectedLocations}
</div>
</div>

<div class=”row pt-5”>
<div class=”col”>
<h5>Type</h5>
<label v-for=”(value, key) in types”>
{value}
<input type=”checkbox” :value=”value” v-model=”selectedTypes”>
</label>
{selectedTypes}
</div>
</div>

<transition-group class=”row” style=”margin-top:30px;” name=”list” tag=”div” mode=”out-in”>
<div class=”col-sm-4 pb-3 list-item” v-for=”(hotel, index) in filteredHotels” :key=”index”>
<div class=”sau-card”>
<i class=”fal fa-server fa-3x”></i>
<h2>{hotel.name}</h2>
<p>{hotel.type}</p>
<p>{hotel.location}</p>

</div>
</div>
</transition-group>
</div>

Data

data() {
return {
locations:[‘Sydney’,’Melbourne’],
types:[‘backpackers’,’hotel’,’resort’],
selectedLocations:[],
selectedTypes:[],
hotels:[
{name:’a Hotel’,location:’Sydney’, type:’backpackers’},
{name:’b Hotel’,location:’Sydney’, type:’hotel’},
{name:’c Hotel’,location:’Sydney’, type:’resort’},
{name:’d Hotel’,location:’Melbourne’,type:’hotel’},
{name:’e Hotel’,location:’Melbourne’, type:’resort’},
{name:’f Hotel’,location:’Melbourne’, type:’hotel’},

]
}
},

Computed

computed:{
filteredHotels(){
if(this.selectedLocations.length){
return this.hotels.filter(j => this.selectedLocations.includes(j.location))
}
else if(this.selectedTypes.length){
return this.hotels.filter(j => this.selectedTypes.includes(j.type))
}
else{
return this.hotels;
}
}
}

Fiddle

Solution :

Here is a working example:

I’ve updated the condition under computed property as below: Include only location which is being selected. Instead of just returning the current selected location.

computed:{
filteredHotels(){
console.log(this.selectedLocations);
if(!this.selectedLocations.length) {
return this.hotels;
} else {
return this.hotels.filter(j => this.selectedLocations.includes(j.location))
}
}
}

new Vue({
el: “#app”,
data: {
locations: [‘Sydney’, ‘Melbourne’],
types: [‘backpackers’, ‘hotel’, ‘resort’],
selectedLocations: [],
selectedTypes: [],
filtersAppied: [],
hotels: [{
name: ‘a Hotel’,
location: ‘Sydney’,
type: ‘backpackers’
},
{
name: ‘b Hotel’,
location: ‘Sydney’,
type: ‘hotel’
},
{
name: ‘c Hotel’,
location: ‘Sydney’,
type: ‘resort’
},
{
name: ‘d Hotel’,
location: ‘Melbourne’,
type: ‘hotel’
},
{
name: ‘e Hotel’,
location: ‘Melbourne’,
type: ‘resort’
},
{
name: ‘f Hotel’,
location: ‘Melbourne’,
type: ‘hotel’
},

]
},
methods: {
setActive(element) {
if (this.filtersAppied.indexOf(element) > -1) {
this.filtersAppied.pop(element)
} else {
this.filtersAppied.push(element)
}
},
isActive: function (menuItem) {
return this.filtersAppied.indexOf(menuItem) > -1
},
},
computed: {
filterApplied: function() {
if (this.filtersAppied.indexOf(element) > -1) {
this.filtersAppied.pop(element)
} else {
this.filtersAppied.push(element)
}
},
filteredHotels: function() {
return this.hotels.filter(hotel => {
return this.filtersAppied.every(applyFilter => {
if (hotel.location.includes(applyFilter)) {
return hotel.location.includes(applyFilter);
}
if (hotel.type.includes(applyFilter)) {
return hotel.type.includes(applyFilter);
}
});
});
}
}
})
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}

#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}

li {
margin: 8px 0;
}

h2 {
font-weight: bold;
margin-bottom: 15px;
}

del {
color: rgba(0, 0, 0, 0.3);
}
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id=”app”>
<div>
<div class=”row pt-5”>
<div class=”col”>
{filteredHotels}
<h5>Locations</h5>
<label v-for=”(value, key) in locations”>
{value}
<input type=”checkbox” :value=”value” v-model=”selectedLocations” :checked=”isActive(value)” @click=”setActive(value)”>
</label> {selectedLocations}
</div>
</div>

<div class=”row pt-5”>
<div class=”col”>
<h5>Type</h5>
<label v-for=”(value, key) in types”>
{value}
<input type=”checkbox” :value=”value” v-model=”selectedTypes”
:checked=”isActive(value)”@click=”setActive(value)”>
</label> {selectedTypes}
</div>
</div>

<div class=”row”>
<div class=”col-sm-3 pb-4” v-for=”hotel in filteredHotels”>
<div class=”card text-center”>
<h1>{hotel.name}</h1>
<p>{hotel.location}</p>
</div>
</div>
</div>
</div>
</div>

Hope this helps!

Solution 2:

Pass the data via binding this or using ()=>, e.g:

filteredHotels(){
return this.hotels.filter(function (el) {
return this.selectedLocations.includes(el.location)
|| this.selectedTypes.includes(el.type)
}.bind(this));
}

Fiddle

[Vue.js] How to set a toggle as open by default in Vue.js

I’m trying to set a toggle as open by default in Vue.js, however I’m not really sure where I should use Boolean. Where should I put Boolean “true” or “false”? in Vue.js? In script tag, I’m not sure how I can write Boolean in this code.

Solution :

In data define boolean ‘openMenu’

data: function() {
return {
openMenu : false,
}
}

In HTML

<div id=”nav-content” v-show=”openMenu”>

In method toggle that using SideBarToggle function

methods: {
sideBarToggle(){
this.openMenu = !this.openMenu
}
}

Or toggle from template HTML also

<div class=”mouseover nav-toggle” @click=”openMenu != openMenu”>

[Vue.js] How can I translate app without reloading page in vue.js?

to translate my app English to German.
on the language change event, I wrote this code

changeLocale (locale) {
i18n.locale = locale.language
VueCookies.set(‘UserLanguage’, locale.language)
// window.location.reload() this one is reloading page
this.$root.reload() // this one is not working
},

and to translate this data in vuejs file :

DashboardData: [{‘name’: this.$t(‘IVR’)}, {‘name’: this.$t(‘DTML’)}, {‘name’: this.$t(‘SSH’)}]

if I do window.location.reload(), it’s working perfectly
but I don’t want to reload the page so, when thinking to reload root in vue, when not sure about this.

Is there any way to reload the root element or all property of the whole app?

Solution :

If you are just trying to perform a safe reload via vue.js , there is a simple method you can use …

vm.$forceUpdate();

for further info you can go here

[Vue.js] Vue JS | create new key + value, in a dynamic builded array ($ajax)

What we are trying to accomplish is an calender in Vue.js, the calender gets the values using an $ajax call. After this i would like to manipulate some of the childrens data in vue.js.

I spend 2 hours+ to find a potential method to use this, However i cant seem to find the way to target a property in the dynamic children of the data object.

The last thing i tried is using a ‘$refs’ call, this sorta is doing the thing i need. But i think i cant manipulate the childrens data this way.

My vue.js object is looking like this at the moment:

var app = new Vue({
el: ‘#aankomende-week’,
data: {
calendar: ‘’
},
methods: {
deleteAll(){
app.calendar = ‘’;
},
callAJAX() {
$.post(
‘/ajax/calendar’,
‘’,
function (response) {
app.calendar = response;
},
‘json’
);
console.log(this.$refs);
}
},
created: function(){
this.callAJAX();
}

});

And my template is like this:

And my data array is looking like:

is there a way i can set a new property something like:

this.calendar.events.[child].totalTime = this.calender.events.[child].end - this.calender.events.[child].start;

this.calender.events.[index].totalTime = this.calender.events.[index].end - this.calender.events.[index].start;

this.calender.events.[anything].totalTime = this.calender.events.[anything].end - this.calender.events.[anything].start;

It would be great to have it in a watcher (So if any values change, it does the building/calculating of the array key again)

Solution :

Given that app.calendar.events is an array..

var app = new Vue({
el: ‘#aankomende-week’,
data: {
calendar: ‘’
},
methods: {
deleteAll(){
app.calendar = ‘’;
},
callAJAX() {
$.post(
‘/ajax/calendar’,
‘’,
function (response) {
app.calendar = response;
this.addNewData();
},
‘json’
);
},
addNewData() {
app.calendar.events.map(function(event) {
event.data = ‘some value’;
});
}
},
created: function(){
this.callAJAX();
}

});

I’ve added a method call in the response, named addNewData. I’ve added this method in the methods object. It does a map on the events array and for each event you can add a certain property. It will return an array with the property added. More info on map here

Solution 2:

There are 2 problems with the code

1.You are setting the value of the ajax response using app.calendar, you should use this.calendar=response

2.Second you need to use Vue.set to add a new property, or insert a value into an array actually. More about this here. One note about this, you can’t add top level data properties using Vue.set.

Solution 3:

Vue.set( target, key, value ) Arguments:

{Object | Array} target

{string | number} key

{any} value

Returns: the
set value.

Usage:

Adds a property to a reactive object, ensuring the new property is
also reactive, so triggers view updates. This must be used to add new
properties to reactive objects, as vue.js cannot detect normal property
additions (e.g. this.myObject.newProperty = ‘hi’).

The target object cannot be a vue.js instance, or the root data object of
a vue.js instance.

vue.js Docs