link1370 link1371 link1372 link1373 link1374 link1375 link1376 link1377 link1378 link1379 link1380 link1381 link1382 link1383 link1384 link1385 link1386 link1387 link1388 link1389 link1390 link1391 link1392 link1393 link1394 link1395 link1396 link1397 link1398 link1399 link1400 link1401 link1402 link1403 link1404 link1405 link1406 link1407 link1408 link1409 link1410 link1411 link1412 link1413 link1414 link1415 link1416 link1417 link1418 link1419 link1420 link1421 link1422 link1423 link1424 link1425 link1426 link1427 link1428 link1429 link1430 link1431 link1432 link1433 link1434 link1435 link1436 link1437 link1438 link1439 link1440 link1441 link1442 link1443 link1444 link1445 link1446 link1447 link1448 link1449 link1450 link1451 link1452 link1453 link1454 link1455 link1456 link1457 link1458 link1459 link1460 link1461 link1462 link1463 link1464 link1465 link1466 link1467 link1468 link1469 link1470 link1471 link1472 link1473 link1474 link1475 link1476 link1477 link1478 link1479 link1480 link1481 link1482 link1483 link1484 link1485 link1486 link1487 link1488 link1489 link1490 link1491 link1492 link1493 link1494 link1495 link1496 link1497 link1498 link1499 link1500 link1501 link1502 link1503 link1504 link1505 link1506

[Vue.js] Laravel Array to string conversion on multiple records

I’m trying to salve multiple records at once..

When I try to store multiple records it gives an error of array to string conversion.

This is the response I get from axios.

array:2 [
0 => array:3 [
“property_type_id” => 2
“fee_value” => “123”
“product_service_id” => 1
]
1 => array:3 [
“property_type_id” => 1
“fee_value” => “3333”
“product_service_id” => 1
]
]

$feeByPropertyType = $request->feeByPropertyType;

foreach ($feeByPropertyType as $row)
{
$data[] = [
‘property_type_id’ => $row[‘property_type_id’],
‘fee_value’ => $row[‘fee_value’],
‘product_service_id’ => 1
];
}
PaymentTypeProductService::insert($data);

there is tried a few other methods as well but none of them have worked so far.

Any help from the community will be greatly appreciated, on how to correct this.

Solution :

You need to format the $data to be like this.

[
[
‘property_type_id’ => 2,
‘fee_amount’ => “123”
],
[
‘property_type_id’ => 1,
‘fee_amount’ => “1312”
],
]

Solution 2:

In this case, if the data structure of the $request->feeByPropertyType data structure matches with the database tables structure, then you can simply use DB facade to insert multiple rows at once.

DB::insert($request->feeByPropertyType);

[Vue.js] Can't create REST API with a longer path

I’m a total beginner with node, and I’ve looked everywhere for answer, but I can’t seem to resolve this issue. I’m using express, mongoose and Vuex.

I basically want to define two endpoints-one for getting photos for a specific user, and another that gets all photos by all users. My first endpoint is /api/photos, and it works perfectly, but /api/photos/all always catches an error. However, I know that there’s nothing wrong with the way I’m making the request in Vuex because if I replace the code inside /photos with the code intended for /photos/all it works. I’ve tried all kinds of alternatives to /photos/____ but it seems like it doesn’t like the path? The node error doesn’t help because it says

CastError: Cast to ObjectId failed for value “all” at path “_id” for model “Photo”

but I know that’s not the issue, because both calls work when I define the endpoint as /photos instead.

Here’s my store.js

async getAllPhotos(context) {
try {
let response = await axios.get(“/api/photos/all”);
context.commit(‘setPhotos’, response.data);
return “”;
} catch (error) {
return “”;
}
},
async getOnePhoto(context, id) {
try {
let response = await axios.get(“/api/photos/“ + id);
context.commit(‘setSelectedPhoto’, response.data);
} catch (error) {
return “”;
}
},

my photo.js:

const mongoose = require(‘mongoose’);
const express = require(“express”);
const router = express.Router();
const auth = require(“./auth.js”);

// Configure multer so that it will upload to ‘/public/images’
const multer = require(‘multer’)
const upload = multer({
dest: ‘../public/images/‘,
limits: {
fileSize: 10000000
}
});

const users = require(“./users.js”);
const User = users.model;

const photoSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.ObjectId,
ref: ‘User’
},
path: String,
title: String,
description: String,
name: String,
created: {
type: Date,
default: Date.now
},
});

const Photo = mongoose.model(‘Photo’, photoSchema);
// get photos for user
router.get(“/“, auth.verifyToken, User.verify, async (req, res) => {
try {
let photos = await Photo.find().sort({
created: -1
}).populate(‘user’);
return res.send(photos);
} catch (error) {
console.log(error);
return res.sendStatus(500);
}
});

// get all photos THIS DOESNT WORK NO MATTER WHAT CODE GOES IN
router.get(“/all”, async (req, res) => {
// return photos
try {
let photos = await Photo.find({
user: req.user
}).sort({
created: -1
});
return res.send(photos);
} catch (error) {
console.log(error);
return res.sendStatus(500);
}
});

// get individual photo
router.get(“/:id”, async (req, res) => {
try {
// console.log(“I’m here”)
let photo = await Photo.findOne({
_id: req.params.id
});
res.send(photo);
} catch (error) {
console.log(error);
res.sendStatus(500);
}
})

and my server.js:

const express = require(‘express’);
const bodyParser = require(“body-parser”);

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));

const mongoose = require(‘mongoose’);

// connect to the database
mongoose.connect(‘mongodb://localhost:27017/photobomb’, {
useNewUrlParser: true
});

const cookieParser = require(“cookie-parser”);
app.use(cookieParser());

const users = require(“./users.js”);
app.use(“/api/users”, users.routes);

const photos = require(“./photos.js”);
app.use(“/api/photos”, photos.routes);

const comments = require(“./comments.js”);
app.use(“/api/comments”, comments.routes);

app.listen(4000, () => console.log(‘Server listening on port 4000!’));

Solution :

The cast error is pointing that you might be using a wrong parameter to find the data,From looking a the above code i reckon you are trying to retrieve all the photos of the queried user,If that is the case user schema must have photo key associated to photos collection with objectId’s like shown below, hence you can query for the user and populate the images parameter,which would give list of images associated to the user .Look for collection association in mongoose with OBJECTID What’s Mongoose error Cast to ObjectId failed for value XXX at path “_id”? this link explains the error you got.hope its of some help to you

{
“user”:String,
“images”:[“imgs”:{
“type”:mongoose.Schema.Types.ObjectId,
“ref”:”Photos”
}]

}

[Vue.js] How to acces external json file objects in vue.js app

How to access JSON objects in the vue.js app when new in this

import json from ‘./json/data.json’

the JSON file is loaded and now there is to access the objects within it

Solution :

Just assign the import to a data property

<script>
import json from ‘./json/data.json’
export default{
data(){
return{
myJson: json
}
}
}
</script>

then loop through the myJson property in the template using v-for

<template>
<div>
<div v-for=”data in myJson”>{data}</div>
</div>
</template>

NOTE

If the object you want to import is static i.e does not change then assigning it to a data property would make no sense as it does not need to be reactive.

vue.js converts all the properties in the data option to getters/setters for the properties to be reactive. So it would be unnecessary and overhead for vue.js to setup getters/setters for data which is not going to change. See Reactivity in depth.

So you can create a custom option as follows:

<script>
import MY_JSON from ‘./json/data.json’
export default{
//custom option named myJson
myJson: MY_JSON
}
</script>

then loop through the custom option in the template using $options:

<template>
<div>
<div v-for=”data in $options.myJson”>{data}</div>
</div>
</template>

Solution 2:

If the file looks like this:

[
{
“firstname”: “toto”,
“lastname”: “titi”
},
{
“firstname”: “toto2”,
“lastname”: “titi2”
},
]

You can do:

import json from ‘./json/data.json’;
// ….
json.forEach(x => { console.log(x.firstname, x.lastname); });

[Vue.js] the $emit Vue method on parent does't work , but on child it works

there is a component register and add event @submit.prevent inside the template by $emit , i tried to console.log on the inisde method component, it was works, but when on my main js, it does not work and nothing, but not error

this is my component example :

Vue.component(“register”, {
props: {
form: Object
},
template: `
<div class=”container”>
<div class=”row”>
<div class=”col-sm-4 offset-4”>
<form @submit.prevent=”goRegister”>
<div class=”form-group”>
<label for=”username”>username</label>
<input type=”text” class=”form-control” id=”usernameRegister” aria-describedby=”emailHelp” placeholder=”Enter username” v-model.trim=”form.username” required>
</form>
</div>
</div>
</div>
`,
methods: {
goRegister() {
this.$emit(“doRegister”, this.form);
}
}
});

this is my parent on my html :

<register v-on:do-register=”handleRegister” :form=”forms”> </register>

and on my vue.js main js

new Vue({
data:{
forms: {
username: null,
email: null,
password: null,
name: null,
age: null
}
},
methods : {
handleRegister() {
console.log(this.forms.username);
}
}
})

i tried to console that method handleRegister, but nothing happened and not error,
is that something missing on my parent component ??

Solution :

Just rename the event you are emitting: VueJS does not convert between camelCase and kebab-case for emitted event names. If you want to listen to the do-register event, you need to emit the event as do-register and not doRegister:

this.$emit(‘do-register’, this.form);

What if you still want to emit a doRegister event? In that case, you will need to emit it as an all-lowercase string.

Note that bound event names inline has to be case-insensitive, due to a limitation in HTML, where attribute names are case-insensitivethe browser actually converts it to lowercase. Therefore, if you still prefer to emit an event without using the kebab-case nomenclature, then you will need to do:

this.$emit(‘doregister’, this.form);

And in the consuming parent’s template, you will need to listen to the doregister event:

<register v-on:doregister=”handleRegister” :form=”forms”> </register>

[Vue.js] Proper way to pass and loop through array in vue-chartjs

I’m working with Laravel 5.7 and have been using vue-chartjs.

Expected outcome:

to pass an array to vue.js and loop through specific values to dynamically create a chart.

What I’ve been trying:

there is the following array:

0 => array:4 [
“order_date” => “2019-04-01”
“days_remaining” => 29
“cash_remaining” => 26714.63
“ratio” => “1.11”
]
1 => array:4 [
“order_date” => “2019-04-02”
“days_remaining” => 28
“cash_remaining” => 26184.61
“ratio” => “1.41”
]

I’m passing the array to my vue.js component using the :bind shorthand in my blade.

:chart-data=”{ json_encode($array) }”

I was reading about using a sequential for loop, but whenever I try and add a for loop, I get an Uncaught Error: Module build failed: SyntaxError: Unexpected token (19:11) error.

<script>
import { Line } from ‘vue-chartjs’

export default {
extends: Line,
props: [‘chartData’],

mounted() {
console.log(this.chartData); // This works
var length = this.chartData.length; // So does this

this.renderChart({
labels: [‘Ratio Value’],

// This produces the error listed above
for ( var i = 0; i < length; i++ )
{
console.log(chartData[i]);
}

datasets: [
// to dynamically produce the following
{
label: [chartData.order_date],
data: chartData.ratio
}
]
})
}
}
</script>

The array length is constant at 5, so I could just store their values in hidden inputs in my blade template and make use of document.querySelector, but this seems clunky and not the best route.

Any advice would be extremely appreciated!

Solution :

Move the for() out of the renderChart() call:

import { Line } from ‘vue-chartjs’

export default {
extends: Line,
props: [‘chartData’],

mounted() {
var length = this.chartData.length;
var array = this.chartData;

// Create new arrays to store the data
var ratioArray = [];
var labelsArray = [];

for ( var i = 0; i < length; i++ ) {
// Then push our data to the new arrays
labelsArray.push(array[i] ? array[i].order_date : ‘’);
ratioArray.push(array[i] ? array[i].mbr : ‘’);
}

this.renderChart({
labels: labelsArray, // Reference our new labelsArray
datasets: [
{
label: ‘Ratio’,
data: ratioArray, // And our new ratioArray
}
]
})
}
}

You can’t call functions when initializing objects.

[Vue.js] How to pass the id value of an url with axios and javascript for a single element

I’m showing the data parameters (name, height, mass…) for a character using the swapi (https://swapi.co/), AXIOS and VUE.

I already have the url for a character (i.e http://localhost:8081/person/1) and it to match with the swapi API (https://swapi.co/api/people/1/), but I don’t know where is my error

I’m using Axios and Vue, I’ve made a service for the Axios get request and the method to get the information in my vue.js file.

The code for my “people.service.js” service is this:

import axios from “axios”;

const PeopleService = {};

// PeoplesService.getPeoples = async () => {}; - Para sacar el listado de planetas con un v-for

PeopleService.getPeople = async id => {
try {
const result = await axios.get(`people/${id}`);

// For getting the species

const specieRoute = result.data.species[0].split(“/“);
const idSpecie = specieRoute[specieRoute.length - 2];
const especie = await axios.get(`species/${idSpecie}`);

// For getting the planets

const planetRoute = result.data.homeworld.split(“/“);
const idPlanet = planetRoute[planetRoute.length - 2];
const planeta = await axios.get(`planets/${idPlanet}`);

// console logs to show results

console.log(result.data);
console.log(idSpecie);
console.log(especie.data);
console.log(planeta.data);

// data information

const people = {
nombre: result.data.name,
altura: result.data.height,
peso: result.data.mass,
genero: result.data.gender,
piel: result.data.skin_color,
especie: especie.data.name, // Lo saco del servicio de especies
planeta: planeta.data.name // Lo saco del servicio de planetas
};

return people;
} catch (error) {
const errorStatus = error.response.status;
let errorMessage = “”;

if (errorStatus === 404) {
errorMessage = “No se encontr al personaje”;
} else {
errorMessage = “Ocurri un error”;
}

throw new Error(errorMessage);
}
};

export default PeopleService;

And my vue.js file is:

<template>
<div>

The id is { $route.params.id }, and the name is { people.nombre }

</div>
</template>

<script>
import PeopleService from “@/services/people.service”;

export default {
async create() {
this.userId = this.$route.params.id;
this.getUser();
},

data() {
return {
user: null,
loading: false,
error: null,
userId: this.$route.params.id
};
},
methods: {
async getUser() {
try {
this.loading = true;
this.people = null;
this.error = null;
this.people = await PeopleService.getPeople(this.userId);
} catch (error) {
this.error = error.message;
} finally {
this.userId = null;
this.loading = false;
}
}
}
};
</script>

<style lang=”scss” scoped></style>

I expect the result to be the name of the character, but i get “[vue.js warn]: Error in render: “TypeError: Cannot read property ‘nombre’ of undefined”

Solution :

when creating a second answer in order to outline how you could do this using vue-router, since you were asking about it.

Disclaimer: this isn’t the ‘cleanest’ code - this pseudo code is designed to loosely illustrate the objective.

Hope this helps!

CodePen mirror

const PeopleService = {};
PeopleService.getPeople = async id => {
try {
const result = await axios.get(`https://swapi.co/api/people/${id}\`);
const specieRoute = result.data.species[0].split(“/“);
const idSpecie = specieRoute[specieRoute.length - 2];
const especie = await axios.get(`https://swapi.co/api/species/${idSpecie}\`);
const planetRoute = result.data.homeworld.split(“/“);
const idPlanet = planetRoute[planetRoute.length - 2];
const planeta = await axios.get(`https://swapi.co/api/planets/${idPlanet}\`);
const people = {
nombre: result.data.name,
altura: result.data.height,
peso: result.data.mass,
genero: result.data.gender,
piel: result.data.skin_color,
especie: especie.data.name, // Lo saco del servicio de especies
planeta: planeta.data.name // Lo saco del servicio de planetas
};
return people;
} catch (error) {
const errorStatus = error.response.status;
let errorMessage = “”;
if (errorStatus === 404) {
errorMessage = “No se encontr al personaje”;
} else {
errorMessage = “Ocurri un error”;
}
throw new Error(errorMessage);
}
};

const peopleComponent = {
name: ‘people’,
template: “#peopleComponent”,
data() {
return {
userId: null,
peopleArray: [],
peopleObject: null,
error: null
};
},
mounted() {
this.userId = this.$route.params.id;
this.getUser();
},
methods: {
async getUser() {
try {
let person = await PeopleService.getPeople(this.userId);
this.peopleArray.push(person); // add to array
this.peopleObject = person; // assign to object
} catch (error) {
this.error = error.message;
}
}
}
};

const homeComponent = {
name: ‘home’,
template: “#homeComponent”,
}

const routes = [
{ path: ‘’, name: ‘home’, component: homeComponent },
{ path: ‘/people/:id’, name: ‘people’, component: peopleComponent },
]

const router = new VueRouter({ routes });

new Vue({
router
}).$mount(‘#app’);
.nav-links {
background-color: lightgray;
text-align: center;
}
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.0.4/vue-router.min.js"></script>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>

<div id=”app”>
<div>
<router-view></router-view>
</div>
</div>

<script type=”text/x-template” id=”homeComponent”>
<div>
<hr/>
<div class=”nav-links”>
<h2>Home</h2>
<div>
<router-link :to=”{ name: ‘people’, params: { id: 1 } }”>Person 1</router-link>
<br/>
<router-link :to=”{ name: ‘people’, params: { id: 2 } }”>Person 2</router-link>
</div>
</div>
<hr/><br/>
</div>
</script>

<script type=”text/x-template” id=”peopleComponent”>
<div>
<hr/>
<div class=”nav-links”>
<h2>People</h2>
<div>
<router-link :to=”{ name: ‘home’ }”>Home</router-link>
</div>
</div>
<hr/><br/>
<h3>People as ARRAY</h3>
<div v-if=”peopleArray.length > 0”>
<div v-for=”(p, index) in peopleArray” :key=”index”>
<div><b>nombre:</b> { p.nombre }</div>
<div><b>altura:</b> { p.altura }</div>
<div><b>peso:</b> { p.peso }</div>
<div><b>genero:</b> { p.genero }</div>
<div><b>piel:</b> { p.piel }</div>
<div><b>especie:</b> { p.especie }</div>
<div><b>planeta:</b> { p.planeta }</div>
</div>
</div>
<div v-else>
<i>Loading People…</i>
</div>
<br/>
<hr/> — OR —
<hr/><br/>
<h3>People as OBJECT</h3>
<div v-if=”peopleObject != null”>
<div v-for=”(p, index) in peopleObject” :key=”index”>
{ p }
</div>
</div>
<div v-else>
<i>Loading People…</i>
</div>
</div>
</script>

Solution 2:

Edit: it doesn’t appear you have a data.people property set up before assigning a value to it.. Can you try to add a people property under data and try again?


data() {
return {

people: null,

}
}

First and foremost, it is not very clear how you are actually sending requests to swapi.. how are you doing this?

I wrote a modified version of what you’re trying to accomplish using the code, but with the swapi URL.. if you change the code to use the swapi URL instead of localhost, does it work?

CodePen mirror

Code snippet is also available below

Edit: CodePen with routing example - detailed secondary answer has also been posted..

If you’re proxying requests locally

What does the server side configuration look like? Are you using node or something else? How are you actually sending API requests to swapi?

If you’re using a local database

Does the local database have any data in it? You may need to set up a service that pulls down data from the swapi API and saves it to the local database, before trying to query the local database for data.

when also not using any routing, so there could be an issue with the routes? At any rate, I hope this helps:

/**
* People service
*/
const PeopleService = {};
PeopleService.getPeople = async id => {
try {
const result = await axios.get(`https://swapi.co/api/people/${id}\`);
const specieRoute = result.data.species[0].split(“/“);
const idSpecie = specieRoute[specieRoute.length - 2];
const especie = await axios.get(`https://swapi.co/api/species/${idSpecie}\`);
const planetRoute = result.data.homeworld.split(“/“);
const idPlanet = planetRoute[planetRoute.length - 2];
const planeta = await axios.get(`https://swapi.co/api/planets/${idPlanet}\`);
const people = {
nombre: result.data.name,
altura: result.data.height,
peso: result.data.mass,
genero: result.data.gender,
piel: result.data.skin_color,
especie: especie.data.name,
planeta: planeta.data.name
};
return people;
} catch (error) {
const errorStatus = error.response.status;
let errorMessage = “”;
if (errorStatus === 404) {
errorMessage = “No se encontr al personaje”;
} else {
errorMessage = “Ocurri un error”;
}
throw new Error(errorMessage);
}
};

/**
* vue.js app
*/
new Vue({
el: “#app”,
data: {
userId: 1,
peopleArray: [],
peopleObject: null,
error: null
},
mounted() {
this.getUser();
},
methods: {
async getUser() {
try {
let person = await PeopleService.getPeople(this.userId);
this.peopleArray.push(person); // add to array
this.peopleObject = person; // assign to object
} catch (error) {
this.error = error.message;
}
}
}
});
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>

<div id=”app”>
<h3>People as ARRAY</h3>
<div v-if=”peopleArray.length > 0”>
<div v-for=”(p, index) in peopleArray” :key=”index”>
<div><b>nombre:</b> { p.nombre }</div>
<div><b>altura:</b> { p.altura }</div>
<div><b>peso:</b> { p.peso }</div>
<div><b>genero:</b> { p.genero }</div>
<div><b>piel:</b> { p.piel }</div>
<div><b>especie:</b> { p.especie }</div>
<div><b>planeta:</b> { p.planeta }</div>
</div>
</div>
<div v-else>
<i>Loading People…</i>
</div>
<br/><hr/> — OR — <hr/><br/>
<h3>People as OBJECT</h3>
<div v-if=”peopleObject != null”>
<div v-for=”(p, index) in peopleObject” :key=”index”>
{ p }
</div>
</div>
<div v-else>
<i>Loading People…</i>
</div>
</div>

Solution 3:

The correct code for the vue.js file is:

<template>
<div>
<h3>Modo array</h3>
<div v-if=”peopleArray.length > 0”> // Detecta que el id es mayor que 0
<div v-for=”(p, index) in peopleArray” :key=”index”>
<div><b>nombre:</b> { p.nombre }</div>
<div><b>altura:</b> { p.altura }</div>
<div><b>peso:</b> { p.peso }</div>
<div><b>genero:</b> { p.genero }</div>
<div><b>piel:</b> { p.piel }</div>
<div><b>especie:</b> { p.especie }</div>
<div><b>planeta:</b> { p.planeta }</div>
</div>
</div>
<div v-else>
<i>Loading People…</i>
</div>
<br/><hr/> — <hr/><br/>
<h3>Modo objeto</h3>
<div v-if=”peopleObject != null”>
<div v-for=”(p, index) in peopleObject” :key=”index”>
{ p }
</div>
</div>
<div v-else>
<i>Loading People…</i>
</div>
</div>
</template>

<script>
import PeopleService from “@/services/people.service”;

export default {

data() {
return {
userId: null,
loading: false,
peopleArray: [], // Para obtener los valores como array
peopleObject: null, // Para que los valores que devuelva sean como array o como objeto
error: null
};
},
mounted() {
this.userId = this.$route.params.id; // el userId corresponde con el ltimo nmero de la url
this.getUser();
},
methods: {
async getUser() {
try {
this.loading = true;
this.people = null;
this.error = null;
let person = await PeopleService.getPeople(this.userId); // Hace la peticin sobre el userID
this.peopleArray.push(person); // Aadir al array
this.peopleObject = person; // Asignar a objeto
} catch (error) {
this.error = error.message;
} finally {
this.userId = null;
this.loading = false;
}
}
}
};
</script>

<style lang=”scss” scoped></style>

[Vue.js] How access axios response in sweetalert2 confirm dialog

I probably don’t understand promises in full even after reading https://gist.github.com/domenic/3889970, i need to access response from axios in sweetalert confirmation result.

this is my code

axios
.post(“/posts”, this.formData)
.then(response => {
if (typeof response.data.callback !== “undefined”) {
toastr.info(“Created”);
swal.fire({
title: “Success!”,
text: “you created new post”,
type: “success”,
showConfirmButton: true,
confirmButtonText: “Close this”,
allowOutsideClick: false
}).then(result => {
if (result.value) {
window.location.replace(response.data.callback);
}
});;
} else {
toastr.error(“Can’t proccess this request”);
}
this.formLoading = false;
})

the response is undefined, i think i don’t understand how scopes work in js

Solution :

Here is an example you can mirror.. It takes a URL which was received from a successful API call (the URL is in the API response), and then sends another request… this should demonstrate to you that you can do whatever you want there… kick off a different function… literally, *anything you want to do, you can do in that * .then(…) block..

CodeSandbox example (updated with chained alerts and API calls)

EDIT: updated my answer to show how you can use the data you retrieve from the API calls….

// Modal.vue.js component - holds the SweetAlert2

<template>
<div>
<button @click=”swal();”>CLICK ME TO LOAD API DATA USING SWEETALERT2</button>
<div v-if=”name != ‘’”>
<p>Name: { name }</p>
</div>
<div v-if=”homeworld != ‘’”>
<p>Homeworld: { homeworld }</p>
</div>
</div>
</template>

<script>
export default {
data() {
return {
name: “”,
homeworld: “”
};
},
methods: {
swal() {
let self = this;
this.$swal
.fire({
title: “Click OK to load from: https://swapi.co/api/people/1/",
showCancelButton: true,
confirmButtonText: “OK”,
showLoaderOnConfirm: true,
preConfirm: () => {
return this.$axios
.get(“https://swapi.co/api/people/1/")
.then(response => {
if (response.status != 200) {
throw new Error(“Something went wrong”);
}
return response.data;
})
.catch(error => {
this.$swal.showValidationMessage(`Request failed: ${error}`);
});
},
allowOutsideClick: () => !this.$swal.isLoading()
})
.then(result => {
if (result.value) {
let v = result.value;
self.name = v.name;
this.$swal
.fire({
title: “Click Ok to redirect to another API call”,
text: `Going to (name:)”${v.name}”‘s homeworld URL at: “${
v.homeworld
}”`,
showCancelButton: true,
confirmButtonText: “OK”,
showLoaderOnConfirm: true,
preConfirm: () => {
return this.$axios
.get(v.homeworld)
.then(response => {
if (response.status != 200) {
throw new Error(“Something went wrong”);
}
return response.data;
})
.catch(error => {
this.$swal.showValidationMessage(
`Request failed: ${error}`
);
});
},
allowOutsideClick: () => !this.$swal.isLoading()
})
.then(res => {
if (res.value) {
self.homeworld = res.value.name;
this.$swal.fire({
title: “Homeworld”,
text: JSON.stringify(res.value)
});
}
});
}
});
}
}
};
</script>

Solution 2:

I read the comment and you said that callback is a url, i’ve used axios and sweetalert before, it seems that you need to pass the “callback” in json format. Have you done it? If not, this is an example using Laravel. Sorry for my english.

Controller.php


if(isAjax){
return response()->json([‘status’=>’info’,’messages’=>’Winter is coming!’,’rheader’=>’Warning!’]);
}

View (vue.js that uses Sweetalert) , general sweetalert should work too


axios.defaults.headers.common[‘X-Requested-With’] = ‘XMLHttpRequest’;
axios.post(“{route(‘someroute’)}”,{id:xid}) //you can ignore this, this is just passing id to the route
.then(response => {
this.$swal(response.data.rheader, “”+response.data.messages+””, response.data.status);
if(response.data.status==”success”){
$(“#something”)).hide();
}
})
.catch(e => {
this.$swal(“Warning”, “”+e.response.data.messages+””, “warning”);
});

Hope it’ll help someone :)

[Vue.js] Getting this error in nuxt do not mutate vuex store state outside mutation handlers

i’m using nuxt.js and to pass current song time to vuex.

but passing data just working once.

this is my data:

currentSongTime: {
second: 0,
minute: 0,
total: 0
}

mounted:

this.WaveSurfer.on(‘seek’, (position) => {
this.currentSongTime.second = parseInt(position * this.WaveSurfer.getDuration() % 60);
this.currentSongTime.minute = parseInt((this.WaveSurfer.getCurrentTime() / 60) % 60);
this.currentSongTime.total = parseInt(position * this.WaveSurfer.getDuration());

this.$store.commit(‘setCurrentSongTime’, this.currentSongTime);
});

index.js (vuex):

export const state = () => ({
currentAudioTime: {}
});

export const mutations = {
setCurrentSongTime(state, val) {
state.currentAudioTime = val;
}
};

it’s just working once, and after that, i get this error message:

[vuex] do not mutate vuex store state outside mutation handlers.

i don’t know what to do?

Solution :

You are directly setting the component data as Vuex state, and this causes problem because when you modify the component data you also directly mutate the state outside the mutation handlers. A quick fix is to clone this object before assigning it as a vuex state:

this.$store.commit(‘setCurrentSongTime’, JSON.parse(JSON.stringify(this.currentSongTime)));

[Vue.js] Where to send a request , parent component or child component?

After a page is split into multiple components, the data of each component is obtained asynchronously, so the request should be initiated by the parent component and then passed to the child component, or the corresponding request sent directly to the child component.

Solution :

You can pass data to child components using props. But for a bigger application managing this would become harder. So, you need to use a state management library such as Redux or MobX.

Solution 2:

This is a very subjective topic. There are various state management libraries like Redux that help solve this problem. You can even use the own personal preference architecture like MVC / MVVM to build the apps. If you are a beginner then I would suggest you explore first on the own, that will make you understand the pros and cons of the approach you took. Then you can move on to tools like Redux / MobX.

[Vue.js] How to fix Cannot create property 'default' on boolean 'true'

I’ve installed a package that provides pagination component for vue. I’ve followed the documentation to set up everything correctly but when getting this error that there is no idea how to fix.

[vue.js warn]: Error in render: “TypeError: Cannot create property ‘default’ on boolean ‘true’”

This is how my response.data looks like:

Tried changing variables, hardcoding them but everything is out of desperation to fix it. I’ve used google but most of the results are in chinese or they are not working for my case.

<pagination :data=”data”>
<span slot=”prev-nav”>< Previous</span>
<span slot=”next-nav”>Next ></span>
</pagination>

export default {
data() {
return {
data: {},
}
},
mounted() {
this.getResults()
},
methods: {
getResults(page = 1) {
axios.get(‘/api/reviews?page=’ + page).then(response => {
this.data = response.data;
});
},
}
}

Hopefully any of you have a solution.

Solution :

If you are using laravel-vue-pagination there is a open PR similar to the problem
with ‘potential bug’ tag
here’s the link