link822 link823 link824 link825 link826 link827 link828 link829 link830 link831 link832 link833 link834 link835 link836 link837 link838 link839 link840 link841 link842 link843 link844 link845 link846 link847 link848 link849 link850 link851 link852 link853 link854 link855 link856 link857 link858 link859 link860 link861 link862 link863 link864 link865 link866 link867 link868 link869 link870 link871 link872 link873 link874 link875 link876 link877 link878 link879 link880 link881 link882 link883 link884 link885 link886 link887 link888 link889 link890 link891 link892 link893 link894 link895 link896 link897 link898 link899 link900 link901 link902 link903 link904 link905 link906 link907 link908 link909 link910 link911 link912 link913 link914 link915 link916 link917 link918 link919 link920 link921 link922 link923 link924 link925 link926 link927 link928 link929 link930 link931 link932 link933 link934 link935 link936 link937 link938 link939 link940 link941 link942 link943 link944 link945 link946 link947 link948 link949 link950 link951 link952 link953 link954 link955 link956 link957 link958

[Vue.js] How to use Multi External CDN JavaScript file in Vue CLI Component

I tried including external JS files in vue.js Component by various methods mounted(), created() but in the end not any solution worked for me. I’m not sure where I’m missing.
Any help would be much appreciated :)

Here’s the code:

<template>
<div id=”sketchy”></div>
</template>

<script>

export default {
data(){
return {
}
}, mounted() {
if (document.getElementById(‘sketchy’)) return; // was already loaded
var scriptTag = document.createElement(“script”);
scriptTag.src = “https://bootswatch.com/\_vendor/jquery/dist/jquery.min.js";
scriptTag.id = “sketchy”;
document.getElementsByTagName(‘head’)[0].appendChild(scriptTag);
},
mounted() {
if (document.getElementById(‘sketchy’)) return; // was already loaded
var scriptTag = document.createElement(“script”);
scriptTag.src = “https://bootswatch.com/\_vendor/popper.js/dist/umd/popper.min.js";
scriptTag.id = “sketchy”;
document.getElementsByTagName(‘head’)[0].appendChild(scriptTag);
},
mounted() {
if (document.getElementById(‘sketchy’)) return; // was already loaded
var scriptTag = document.createElement(“script”);
scriptTag.src = “https://bootswatch.com/\_vendor/bootstrap/dist/js/bootstrap.min.js";
scriptTag.id = “sketchy”;
document.getElementsByTagName(‘head’)[0].appendChild(scriptTag);
},
}
</script>

<style scoped>

</style>

Solution :

I tried the following approach. The 3 script files were imported in the head tag.

mounted:function(){
// if (document.getElementById(‘sketchy’)) {
// console.log(“loadeddd”);
// return;
// } // was already loaded
var scriptTag = document.createElement(“script”);
// scriptTag.src = “https://bootswatch.com/\_vendor/jquery/dist/jquery.min.js";
scriptTag.setAttribute(‘src’,’https://bootswatch.com/\_vendor/jquery/dist/jquery.min.js?onload=onLoad')
// scriptTag.id = “sketchy”;
//scriptTag.setAttribute(‘id’,’sketchy’);
scriptTag.async=true;
scriptTag.defer=true;
document.getElementsByTagName(‘head’)[0].appendChild(scriptTag);
console.log(“scripttag1 createddd”);

var scriptTag1 = document.createElement(“script”);
scriptTag1.setAttribute(‘src’,’https://bootswatch.com/\_vendor/popper.js/dist/umd/popper.min.js?onload=onLoad');
scriptTag1.async=true;
scriptTag1.defer=true;
document.getElementsByTagName(‘head’)[0].appendChild(scriptTag1);
console.log(“scriptag2 createdd”);

var scriptTag2 = document.createElement(“script”);
scriptTag2.setAttribute(‘src’,’https://bootswatch.com/\_vendor/bootstrap/dist/js/bootstrap.min.js?onload=onLoad');
scriptTag2.async=true;
scriptTag2.defer=true;
document.getElementsByTagName(‘head’)[0].appendChild(scriptTag2);
console.log(“scriptag3 createdd”);

}

[Vue.js] How can I minus the quantity from list table in VueJS?

Good day everyone! Can you help me how can I minus the quantity of list table by using the quantity of cart table? In my console.log when I add more than one item to the cart and click the minus button the quantity of each row are the become the same. The quantity from the list table are not the same. How can I get the right result of each quantity in my cart table? to display the right answer in the bottom of the cart table. Heres my jsfiddle –>
https://jsfiddle.net/2zx9vy3n/20/

minusFromListToCart : function() {
for(var index = 0; index < this.selects.length; index++) {
this.total = parseInt(this.select_quantity) - parseInt(this.input_quantity);
console.log(this.total);
}
}

Solution :

I appreciate the try, but unfortunately there are many small mistakes, like

repeating same product goes separately instead adding to previous,
you need computed method to get remaining counts
reset you count for next product adding in cart
minus quantity from relative product count instantly.

Note : add all validation like what if there is not product available etc.

var app = new Vue({
el: ‘#app’,
data: {
selects: [],
carts : [{
id: null, name: null, cat: null, quantity : null
}],
lists: [
{ id: 1, name: ‘Book’, cat: ‘Category 1’, quantity : 50},
{ id: 2, name: ‘Notebook’, cat: ‘Category 2’, quantity : 60},
{ id: 3, name: ‘Pencil’, cat: ‘Category 3’, quantity : 70}
],
select_id : “”,
select_name : “”,
select_cat : “”,
input_quantity : “”,
select_quantity : “”,
total : 0
},
computed:{
remainingQuantity : function() {
var total_qty = 0;
var selected_qty = 0;
for(let i in this.lists){
total_qty += this.lists[i].quantity;
}
return total_qty;
}
},
methods : {
retrieveList : function(id, name, cat, quantity) {
this.input_quantity =1;
this.select_id = id;
this.select_name = name;
this.select_cat = cat;
this.select_quantity = quantity;

//console.log(this.select_quantity);

},
addToCart : function() {
if(!this.input_quantity){
return false;
}
this.carts.id = this.select_id;
this.carts.name = this.select_name;
this.carts.cat = this.select_cat;
this.carts.quantity = parseInt(this.input_quantity);

console.log(this.carts.quantity);

var selected_index = this.selects.map((e)=>e.id).indexOf(this.select_id);
if(selected_index > -1){
this.selects[selected_index].quantity += parseInt(this.input_quantity);
}else{
this.selects.push({…this.carts});
}

var lists_index = this.lists.map((e)=>e.id).indexOf(this.select_id);
if(lists_index > -1){
this.lists[lists_index].quantity -= parseInt(this.input_quantity);
}

}

}
});
<!DOCTYPE html>
<html>
<head>
<link rel=”stylesheet” href=”https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity=”sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T” crossorigin=”anonymous”>
<script src=”https://cdn.jsdelivr.net/npm/vue/dist/vue.js">
</script>
</head>
<body>
<div id=”app”>
<table border=”1”>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Category</th>
<th>Quantity</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for=”(list, index) in lists”>
<td>{list.id}</td>
<td>{list.name}</td>
<td>{list.cat}</td>
<td>{list.quantity}</td>
<td>
<button @click=”retrieveList(list.id, list.name, list.cat, list.quantity)” data-toggle=”modal” data-target=”#myModal”>Add to cart</button>
</td>
</tr>
</tbody>
</table>

<table border=”1” class=”mt-4”>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Category</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr v-for=”(select, index) in selects”>
<td>{select.id}</td>
<td>{select.name}</td>
<td>{select.cat}</td>
<td>{select.quantity}</td>
</tr>
</tbody>
</table>

<p>Final Quantity : {remainingQuantity}</p>

<div class=”modal fade” id=”myModal” class=”text-dark” tabindex=”1”>
<div class=”modal-dialog”>
<div class=”modal-content”>

<div class=”modal-header”>
<h4 class=”modal-title”>Add Transaction</h4>
<button type=”button” class=”close” data-dismiss=”modal”></button>
</div>

<div class=”modal-body mx-auto” id=”modal-less-input”>
<label for=”input_quantity”>Quantity</label>
<div class=”input-group form-group”>
<input type=”number” class=”form-control col-sm-12” id=”input_quantity” v-model=”input_quantity” name=”input_quantity” placeholder=”Enter Quantity” autofocus required>
</div>

</div>

<div class=”modal-footer”>
<button @click.prevent=”addToCart()” type=”button” class=”btn btn-success” data-dismiss=”modal”><i class=”far fa-save”> </i> Add to Cart</button>
</div>

</div>
</div>
</div>
</div>

<script src=”https://code.jquery.com/jquery-3.3.1.js" integrity=”sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=” crossorigin=”anonymous”></script>
<script src=”https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity=”sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM” crossorigin=”anonymous”></script>

</body>
</html>

[Vue.js] Vue Error the template root requires exactly one element

there is the following components

component

<template>
<!–<post-form/>–>
<div class=”wrapper”>
<b-table :data=”posts”>
<template slot-scope=”props”>
<b-table-column field=”completed” label=”complete”>
<b-checkbox
v-model=”props.row.done”>
</b-checkbox>
</b-table-column>
</template>
</b-table>
</div>
</template>

there is a b-table with buefy. And to import the <post-form /> component from the current component.

However, when I insert the component in the desired location, an error occurs.

<div class=”wrapping”> If I place a component under it, my table is broken.

How can I solve this?

Solution :

We can only have one root element in the template. So, if you want to use as a sibling of div with class wrapper, you need to wrap both of these to a parent div, as below:

<template>
<div>
<post-form/>
<div class=”wrapper”>
<b-table :data=”posts”>
<template slot-scope=”props”>
<b-table-column field=”completed” label=”complete”>
<b-checkbox
v-model=”props.row.done”>
</b-checkbox>
</b-table-column>
</template>
</b-table>
</div>
</div>
</template>

[Vue.js] Preselect option with first of array using v-for and v-model

when trying to preselect the first element option using v-for. I could set the data -> SelectedMonth to “12 mneder” - however the data will be dynamic.

there is tried using :selected(index === 0), however, that does not work with v-model.

<select class=”period-control” v-model=”selectedMonth”>
<option
v-for=”(period, price) in car.months”
v-bind:key=”price”
v-bind:value=”period.month”
\>{ period.month }</option>
</select>

data() {
return {
selectedMonth: “”
};
},
asyncData(context) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
car: [
{
id: “1”,
brand: “VW”,
model: “Transporter”,
variant: “Sport”,
thumbnail:
http://pluspng.com/img-png/cargo-van-png-van-png-transparent-image-1878.png",
mprice: “2700”,
dpayment: “5400”,
months: [
{ month: “12 mneder”, smprice: “1500” },
{ month: “24 mneder”, smprice: “2500” },
{ month: “36 mneder”, smprice: “3500” }
]
},
{
id: “2”,
brand: “Nissan”,
model: “Tekna”,
variant: “Sport”,
thumbnail:
http://pluspng.com/img-png/cargo-van-png-van-png-transparent-image-1878.png",
mprice: “3000”,
dpayment: “5400”,
months: [
{ month: “12 mneder”, smprice: “1500” },
{ month: “24 mneder”, smprice: “2500” },
{ month: “36 mneder”, smprice: “3500” }
]
}
].find(el => el.id === context.params.id)
});
}, 1500);
});
}

The expected result is “12 Mneder” in both cases.

Solution :

how about setting the value of selectedMonth in asyncData directly ?

asyncData(context) {
return new Promise((resolve, reject) => {
const car = …
const selectedMonth = car.months[0].month;
setTimeout(() => {
resolve({
car,
selectedMonth
});
}, 1500);
});
}

[Vue.js] GET file ///dist/build.js net ERR_FILE_NOT_FOUND

there is a vue.js project and when I view the file index.html I get a blank page and when I go to the browser console I see the error

GET file:///dist/build.js net::ERR_FILE_NOT_FOUND

This is in my main.js

import vue.js from ‘vue’
import App from ‘./App.vue’
import Bootstrapvue.js from ‘bootstrap-vue’
Vue.use(BootstrapVue);

import ‘bootstrap/dist/css/bootstrap.css’
import ‘bootstrap-vue/dist/bootstrap-vue.css’

import Jumbotron from ‘./Jumbotron.vue’
Vue.component(‘jumbotron’, Jumbotron)

new Vue({
el: ‘#app’,
render: h => h(App)
//router: router
})

And this is my index.html

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8”>
<title>vuejs-blog</title>
</head>
<body>
<div id=”app”></div>
<script src=”/dist/build.js”></script>
</body>
</html>

Does anyone know how this can be fixed?

Solution :

If you want to use vue.js with .vue.js file components - you need to run a web server with webpack. If you created this project using vue-cli you can just run npm run serve from the command line. Otherwise you have to write a webpack config, in order to transpile the code into something a browser can understand.

This was my first project I ever built with vue.js - it uses multiple files that utilize template literals.. It may help point you in the right direction if you’re interested in learning vue.js without having to mess around with webpack, etc.. (like I wanted to do a first)

You cannot load .vue.js files as you are attempting, and you cannot load module files over the file:// protocol - you need a web server for this ‘advanced’ style of code.

If you want to be able to open an .html file that contains vue.js code - you have to use template literalsfor this.. That article outlines 7 different ways you can build vue.js components - entry #2 outlines how to use template literals.

If you save the following code to an .html file and then double click it - it will work.

<!DOCTYPE html>
<html>

<head>
<meta charset=”utf-8”>
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
<title></title>
<meta name=”description” content=””>
<meta name=”viewport” content=”width=device-width, initial-scale=1”>
<link rel=”icon” type=”image/png” sizes=”16x16” href=””>
</head>

<body>
<div id=”root”>
<!– html will be auto injected –>
</div>
<script src=”https://unpkg.com/vue/dist/vue.js"></script>
<script>
new Vue({
el: ‘#root’,
template: `
<div>
<h1>{ myHeader }</h1>
<p>{ myMessage }</p>
</div>
`,
data: {
myHeader: “Welcome!”,
myMessage: ‘Built using template literal’,
},
});
</script>
</body>

</html>

Solution 2:

@Matt’s right with his solution, but what also worked for me was to run

npm run dev

from the terminal

[Vue.js] Getting an error failed to compile Module not found Error Can't resolve 'babel-loader

Im using vue.js to import google maps to my application

but it does not let me run my application once i import it.

import vue.js from ‘vue’
import App from ‘./App.vue’
import * as VueGoogleMaps from “vue2-google-maps”;

Vue.use(VueGoogleMaps, {
load: {
key: “”,
libraries: “places” // necessary for places input
}
});
new Vue({
el: ‘#app’,
render: h => h(App)
})

and this is the error im getting

Failed to compile.

/Users/temporary/node_modules/vue2-google-maps/dist/components/infoWindow.vue
Module not found: Error: Can’t resolve ‘babel-loader’ in ‘/Users/temporary/node_modules/vue2-google-maps/dist/components’
@ /Users/temporary/node_modules/vue2-google-maps/dist/components/infoWindow.vue.js 4:0-161 5:0-174
@ /Users/temporary/node_modules/vue2-google-maps/dist/main.js
@ ./src/main.js
@ multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server ./src/main.js

Solution :

Are you using vue-cli for this project? If so, you should be able to just do:

npm install –save-dev babel-loader

(or if you’re using yarn)

yarn add –dev babel-loader

If you’re not using vue-cli then you will still need to install babel-loader using the methods above, but you will also have to add it to the webpack config.

More on babel-loader:

From the vue.js docs
More detailed example of babel-loader, vue, and webpack
Example webpack config, taken from the vue2-google-maps GitHub repo

[Vue.js] Object created via spread operator weird behaviour

I’m using Vue.js a spread operator in order to create a new array and find a value inside of it that will be assigned to selectedEmployee data property:

selectEmployee(id) {
const employees = […this.employees];
this.selectedEmployee = employees.find(employee => employee.id === id);
},

Either way, modifying the selectedEmployee value through v-model also modifies the record saved at the paginatedEmployees property which is beign defined like this:

async fetchEmployees() {
this.loading = true;

try {
const response = await axios.get(‘/api/employees’);
this.employees = response.data.employees;
this.paginatedEmployees = _.chunk(this.employees, 10);
this.pages = this.paginatedEmployees.length;
} catch (e) {
this.error = true;
this.requestMessage = e.message;
} finally {
this.loading = false;
}
},

Any idea why this is happening?

Solution :

Spreading makes a shallow copy which means you have a new array of the same employees.

You would want to make a copy of the selected employee instead so you dont mutate the original employee.

Keep in mind this would also be a shallow copy so if the employee has nested objects, those will still reference the originals just like in the array scenario. This is what makes spreading such a cheap operation versus a deep copy/clone.

[Vue.js] How to add button and input element into drop down list

I’ve created a simple select menu (dropdown) using bootstrap Vue. My question is how do I insert a button and an input element inside the dropdown list. Below is an example of what to achieve, and my current code.

Update when still trying to solve this issue, any help is greatly appreciated

Picture1: Button inserted at the bottom of the dropdown list

Picture2: When user clicks on the button, there will be an input field for them to enter a value. The value will automatically be inserted to the dropdown list

Current Code

<template>
<b-container class=”empty-container”>
<b-row align-h=”center”>
<b-col cols=”6”>
<b-form-select v-model=”selected” :options=”options”></b-form-select>
</b-col>
</b-row>
</b-container>
</template>

<script>
export default {
data() {
return {
selected: null,
options: [
{ value: null, text: “Please select an option” },
{ value: “a”, text: “This is First option” },
{ value: “b”, text: “Selected Option” },
{ value: { C: “3PO” }, text: “This is an option with object value” }
]
};
}
};
</script>

<style>
</style>

Solution :

I don’t know if you’ll be able to use the browser’s standard dropdown menu. The reason I’m thinking is that you won’t be able to reliably select the html of browser specific dropdowns. So I would build my own dropdown and if the last option was clicked convert it to an <input type=’text’ > and grab the value from that.

[Vue.js] VueJS child component not rendering data

I’ve got a screen that has divided its main data sections into tabs, and hope to have each tab on its own component.

However, for some reason the data is not showing on the component when it first renders. The thing is, if you click the button to refresh the data it loads just fine. I’m getting no error messages either way, so I think I must be misinterpreting the VueJS lifecycle.

const CommentScreen = {
props: {
accountid: {
type: Number,
required: true
}
},
template: `
<div>
<CommentForm
v-on:commentsupdated=”comments_get”
v-bind:accountid=”accountid”
\></CommentForm>
<v-btn round color=”primary” v-on:click=”comments_get” dark>Refresh Comments</v-btn>
<v-data-table
:headers=”commentheaders”
:items=”comments”
hide-actions>
<template slot=”items” slot-scope=”props”>
<td>{ props.item.entrydate }</td>
<td>{ props.item.entryuserforename + “ “ + props.item.entryusersurname }</td>
<td>{ props.item.comment }</td>
</template>
</v-data-table>
</div>
`,
components: {
‘CommentForm’: CommentForm
},
data(){
return {
commentheaders:[
{ text:’Entry Date’, value:’entrydate’ },
{ text:’Entry User’, value:’entryuserforename’ },
{ text:’Comment’, value:’comment’ }
],
comments:[]
}
}
,
mounted() {
this.comments_get();
},
methods:{
comments_get(){
let url = new URL(‘/comments/‘, document.location);
url.searchParams.append(‘accountid’,this.accountid);

let options = {
method: ‘GET’,
mode: ‘cors’,
headers: {
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json;charset=UTF-8’
}
};

self = this;
fetch(url, options)
.then(
response => {
if (response.status === 401) {
self.$root.$emit(‘notloggedin’);
} else if (response.status === 403) {
self.$root.$emit(‘displayalert’,’Missing Permission: View Comments’);
} else if (response.status === 204) {
self.comments = [];
} else if(!response.ok) {
response.json()
.then(data => self.$root.$emit(‘displayalert’, data.errors))
.catch(error => self.$root.$emit(‘displayalert’, error.status + ‘ ‘ + error.statusText));
} else {
response.json()
.then(data => self.comments = data.comments)
.catch(error => self.$root.$emit(‘displayalert’, error));
}
}
)
.catch(error => self.$root.$emit(‘displayalert’, error));
}
}
};

Forgive the amount of code dumped above, I’m not sure what I could/should remove to make the question more brief.

Can anyone please advise how I can have the data load automatically on this component when its first loaded?

Many thanks in advance.

Solution :

The mounted hook is async, which makes this kind of tricky.

Example of something similar to what you’re trying to do..

new Vue({
el: “#app”,
data: {
placeId: 1,
sight: “”,
sightImages: [],
slideIndex: 1
},
mounted() {
var self = this;
fetch(`https://jsonplaceholder.typicode.com/albums/${this.placeId}/photos?\_start=1&\_end=10\`)
.then(response => {
if (response.ok) {
return response;
} else {
if (response.status === 401) {
alert(“401”);
//self.$root.$emit(“notloggedin”);
}
if (response.status === 403) {
alert(“403”);
//self.$root.$emit(“displayalert”, “Missing Permission: View Comments”);
}
if (response.status === 204) {
alert(“204”);
//self.comments = [];
}
}
})
.then(response => response.json())
.catch(error => {
console.log(“ERROR “ + error);
})
.then(data => {
self.sight = {
id: data[0].albumId
};
self.sightImages = data;
})
/** IF YOU REMOVE THIS THINGS WONT WORK RIGHT */
.then(() => {
self.showSlides(self.slideIndex);
});
/** */
},
methods: {
showSlides(n) {
let i;
let slides = document.getElementsByClassName(“mySlides”);
let dots = document.getElementsByClassName(“demo”);
let captionText = document.getElementById(“caption”);

if (n > slides.length) {
this.slideIndex = 1;
}
if (n < 1) {
this.slideIndex = slides.length;
}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = “none”;
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(“ active”, “”);
}
console.log(slides[0]);
console.log(document.getElementsByClassName(“mySlides”).length);
slides[this.slideIndex - 1].style.display = “block”;
dots[this.slideIndex - 1].className += “ active”;
captionText.innerHTML = dots[this.slideIndex - 1].alt;
},
plusSlides(n) {
this.showSlides((this.slideIndex += n));
},
currentSlide(n) {
this.showSlides((this.slideIndex = n));
}
},
});
.demo-cursor {
width: 3% !important;
cursor: pointer;
margin: 0px 2px
}

.sight-photos {
width: 6%;
}

.row {
display: inline-block;
}

.cntrlbtn {
cursor: pointer;
}
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>

<div id=”app”>
<div class=”wrapper”>
<div class=”sight-container”>
<p class=’sight-name’>Sight Id: { sight.id }</p>
<div class=”photos-container”>
<div v-for=’(image, index) in sightImages’ class=”mySlides”>
<div class=”numbertext”>{ index + 1 } / { sightImages.length }</div>
<img class=’sight-photos’ :src=”image.thumbnailUrl”>
</div>
<a class=”cntrlbtn” @click=’plusSlides(-1)’></a>
<a class=”cntrlbtn” @click=’plusSlides(1)’></a>
<div class=”caption-container”>
<p id=”caption”></p>
</div>
<div class=”row”>
<img v-for=’(image, index) in sightImages’ class=”demo-cursor” :src=”image.url” @click=”currentSlide(index + 1)”>
</div>
</div>
</div>
</div>
</div>

You could try something like this:

const self = this;
fetch(url, options)
.then(response => {
if (response.ok) {
return response;
} else {
if (response.status === 401) {
self.$root.$emit(“notloggedin”);
}
if (response.status === 403) {
self.$root.$emit(“displayalert”, “Missing Permission: View Comments”);
}
if (response.status === 204) {
self.comments = [];
}
}
})
.then(response => response.json())
.catch(error => {
self.$root.$emit(“displayalert”, error);
})
.then(data => {
self.comments = data.comments;
});

[Vue.js] How to sort array when variable names have quotes in JavaScript?

I’m making a vue.js front-end feature that could filter data by keywords and sort data in either ascending or descending order. And I found this code online which might meet my requirements. However the format of its data array is different from my retrieved array:

<template>
<div id=”app”>
<br /><br />
<div>
<input type=”text” v-model=”filterValue” placeholder=”Filter”>
<button @click=”invertSort()”>Sort asc/desc</button>
</div>
<table class=”table table-striped”>
<thead>
<tr>
<td>Name</td>
<td>Value</td>
</tr>
</thead>
<tbody>
<tr v-for=”data in filteredAndSortedData”>
<td>{data.name}</td>
<td>{data.val}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
testData: [{name:’3’, val:’a’}, {name:’2’, val:’b’}, {name:’1’, val:’c’}, {name:’4’, val:’d’}],
error: “”,
errorFlag: false,
filterValue: “”,
sortAsc: true
};
},
computed: {
filteredAndSortedData() {
// Apply filter first
let result = this.testData;
if (this.filterValue) {
result = result.filter(item => item.name.includes(this.filterValue));
}
// Sort the remaining values
let ascDesc = this.sortAsc ? 1 : -1;
return result.sort((a, b) => ascDesc * a.name.localeCompare(b.name));
}
},
methods: {
invertSort() {
this.sortAsc = !this.sortAsc;
}
},
}
</script>

So in the provided function its array is like testData: [{name:’1’, val:’a’}], however, my array which retrieved by using this.testData = response.data in function(response) is like testData: [{“name”:”1”, “val”:”a”}]
That being said, my variable names are double-quoted and cannot use the code I want. Is there a way to convert [{“name”:”1”, “val”:”a”}] to [{name:’1’, val:’a’}] (like removing variable names quotes) or sort it without modifying the array?

Solution :

you can get object key sting using

var a = [{“name”:”1”, “val”:”a”}];
console.log(a[0][“name”])
// if you already know key
console.log(a[0].name)

and this [{“name”:”1”, “val”:”a”}] and [{name:’1’, val:’a’}] is same in javascript.