link411 link412 link413 link414 link415 link416 link417 link418 link419 link420 link421 link422 link423 link424 link425 link426 link427 link428 link429 link430 link431 link432 link433 link434 link435 link436 link437 link438 link439 link440 link441 link442 link443 link444 link445 link446 link447 link448 link449 link450 link451 link452 link453 link454 link455 link456 link457 link458 link459 link460 link461 link462 link463 link464 link465 link466 link467 link468 link469 link470 link471 link472 link473 link474 link475 link476 link477 link478 link479 link480 link481 link482 link483 link484 link485 link486 link487 link488 link489 link490 link491 link492 link493 link494 link495 link496 link497 link498 link499 link500 link501 link502 link503 link504 link505 link506 link507 link508 link509 link510 link511 link512 link513 link514 link515 link516 link517 link518 link519 link520 link521 link522 link523 link524 link525 link526 link527 link528 link529 link530 link531 link532 link533 link534 link535 link536 link537 link538 link539 link540 link541 link542 link543 link544 link545 link546 link547

[Vue.js] .then(Response => SyntaxError Unexpected token ., in Vue js

I’m currently learning vue.js and following a Udemy course. My empty vue.js project is however a bit more strict in notation than my teachers. So while I’m trying to figure it all out, I’m also sometimes getting unexpected token errors.

I don’t really understand why when getting a unexpected token error on .then.
This might be something very simple that I don’t yet see as a mistake.

I checked everything to see if everything has a closing tag, has commas and semicolons.

actions: {
signIn({ commit }, payload) {
Vue.http.post(`${FbAuth}/verifyPassword?key=${FbApiKey}`, {
…payload,
returnSecureToken: true,
}),
.then( response => response.json())
.then( authData => {
console.log(authData);
}),
},
},

It should pass the signin action and check my firebase database for the needed credentials.

Solution :

You have a comma before the dot.
Try this follow code:

actions: {
signIn({ commit }, payload) {
Vue.http.post(`${FbAuth}/verifyPassword?key=${FbApiKey}`, {
…payload,
returnSecureToken: true,
})
.then( response => response.json())
.then( authData => {
console.log(authData);
}),
},
},

[Vue.js] Implement a pop up box after a successful axios post

there is an action

storeExpense(context, params){
axios.post(‘api/expenses’, params)
.then( response => {
context.dispatch(‘getExpenses’)
})
.catch( error => {
context.commit(‘errors’, error.response.data.errors)
//console.log(error.response.data.errors);
})
}

and then on my component when the user click the submit button I just called the action via dispatch

store(){
this.$store.dispatch(‘storeExpense’,this.expense)
}

Now there is sweetalert I’m confused how to implement it after a successful axios post request

I tried to put it inside my action like this

storeExpense(context, params){
axios.post(‘api/expenses’, params)
.then( response => {
context.dispatch(‘getExpenses’)
this.$swal(
‘Success’,
‘Expense has been updated!’,
‘success’
)
})
.catch( error => {
context.commit(‘errors’, error.response.data.errors)
//console.log(error.response.data.errors);
})
}

but nothing happened because it is on the action file. Should I call it inside my component like this?

this.$store.dispatch(‘storeExpense’,this.expense)
.then( response => {
this.$swal(
‘Success’,
‘Expense has been created!’,
‘success’
)

Any idea on how can I implement this? Thanks

Im beginner in vuejs and vuex.

Solution :

I think the key question is that “this” may be not the “this” you want in store module, “this” in store module is different from “this” in components.
So change the way you want to alert

import swa in the store module

import Swal from ‘sweetalert2/dist/sweetalert2.js’
do alert when axios compolete use code below

Swal.fire({
title: ‘Error!’,
text: ‘Do you want to continue’,
type: ‘error’,
confirmButtonText: ‘Cool’
})
never forget import swa’s css file in main js

[Vue.js] Drawn polygon does not show in openlayers

there is to draw a polygon on openlayers Map. This is my code:

draw = new Draw({
source: this.vectorSource,
type: ‘Polygon’
})
draw.on(‘drawend’, e => {

// sol 1, result is not as required
let coords = e.feature.getGeometry().getCoordinates()

//sol 2, give correct results, but drawn polygon gone
let coords = e..feature.getGeometry().transform(‘EPSG:3857’, ‘EPSG:4326’).getCoordinates()
}
this.olmap.addInteraction(draw)

there is to store the transformed coordinates in DB, but solution #2 does not maintain the visibility of drawn poloygon.
In case of solution #1, it does not gives the required formated coordinates, if I try to transform them later using

transform(coords, ‘EPSG:3857’, ‘EPSG:4326’)

it does not return formated coordinates.
please guide me where when wrong to maintain the visibility of polygon and get the transformed coordinates.

Solution :

You need to clone the geometry

let coords = e..feature.getGeometry().clone().transform(‘EPSG:3857’, ‘EPSG:4326’).getCoordinates();

otherwise you wil move the feature somewhere close to point [0, 0] in view cooordinates

[Vue.js] Search multiple fields in a table in Vue.js with different v-model

when new to vue.js. I was trying to filter the table columns using multiple search fields. there is different search fields and their respective v-models for different columns in the table. to enable search for each column

I tried the following solutions:
1. Vue.js filterBy to search in multiple fields
2. How do I search through multiple fields in Vue.js 2

Using the above two solutions I came up with this:

<p>
<label>First Name</label>
<input type=”text” placeholder=”Enter firstname” v-model=”First” />
</p>

<p>
<label>Last Name</label>
<input type=”text” placeholder=”Enter the last Name” v-model=”Last” />
</p>

<p>
<label>CustomerId</label>
<input type=”text” placeholder=”Enter the CustomerId” v-model=”CustomerId” />
</p>

<table id=”clients”>
<thead>
<tr>
<th width=”40%”>First Name</th>
<th width=”20%”>Last Name</th>
<th width=”20%”>CustomerId</th>
</tr>
</thead>

<tbody v-for=”customer in filteredCustomers.slice(0,20)”>

<tr>
<td>{customer.first}</td>
<td>{customer.last}</td>
<td>{customer.id}</td>

</tr>

</tbody>
</table>

Script:

export default {
props:[‘showMod’],

data() {

return {
id: ‘’,
First: ‘’,
Last: ‘’,
CustomerId: ‘’,
categories: []
}
},

computed: {

filteredCustomers: function () {
var self = this;
return this.categories.filter(function (cust) {
return cust.first.toLowerCase().indexOf(self.First.toLowerCase()) >-1 || cust.last.toLowerCase().indexOf(self.Last.toLowerCase()) >-1
});
}

I change the code to enable search on only one field, it works but stops working when trying to search on multiple fields.
I don’t know what when doing wrong in this.

Edit:
I was able to get those search working independently by adding “if”

filteredCustomers: function () {
var self = this;
return this.categories.filter(function (cust) {
if (self.First) {
return cust.first.toLowerCase().indexOf(self.First.toLowerCase()) > -1
}
if (self.CustomerId) {
return cust.clientId.toLowerCase().indexOf(self.CustomerId.toLowerCase()) > -1
}

return cust.last.toLowerCase().indexOf(self.Last.toLowerCase())>-1
});

Hoewever, I could not get two filter conditions working at the same time like first search based on first name and then search on last name.

Solution :

You just need to adjust the logic:

filteredCustomers() {
return this.categories.filter(customer => {
return (!this.First || customer.first.toLowerCase().includes(this.First.toLowerCase()))
&& (!this.Last || customer.last.toLowerCase().includes(this.Last.toLowerCase()))
});

You could also use regular expressions and .match() if you didn’t want to bother with the lower case conversion.

[Vue.js] Read text file with vuetify-upload-button

I need to read uploaded text file in VueJS App with Vuetify. I found that there’s no input file element so I use vuetify-upload-button package.

However, it seems that there’s no way to read it.

Is it possible to read file using vuetify upload-btn tag?

HTML

<upload-btn
title=”Choose File”
block
color=”green”
@file-update=”updateFile”
\></upload-btn>

JS

updateFile(x) {
const reader = new FileReader();
const file = e.target.files[0];
reader.onload = e => console.log(e.target.result);
reader.readAsText(file);
}

Solution :

The package you’re using returns e.target.files if multiple or e.target.files[0] if singular. You have no access to the event through this package.

So in the case — for singular, the entire method can be:

updateFile(file) {
const reader = new FileReader()

reader.onload = e => console.log(e.target.result)

reader.readAsText(file)
}

[Vue.js] How can I get the child component after adding data before render?

to set some props of the child component after adding data, but how can I do it?

For the example below, to select the item added in the methods additem(), how can I implement it in Vue?

Vue.component(‘list-item’, {
props: [‘text’],
data() {
return {
selected: false,
}
},
methods: {
click() {
this.selected = true;
}
},
template: `
<li v-bind:class=”{ selected : selected }” v-on:click=”click”>{text}</li>
`
});

var idx = 0;
Vue.component(‘list’, {
data() {
return {
list: [],
}
},
methods: {
additem() {
this.list.push(“li “ + idx++);
}
},
template: `
<div>
<button v-on:click=”additem”>Add</button>
<ul>
<list-item v-for=”item in list” v-bind:text=”item”></list-item>
</ul>
</div>
`
});

var demo = new Vue({
el: “#demo”
});
<!DOCTYPE html>
<html>
<head>
<meta charset=”UTF-8” />
<script src=”https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<style>
li.selected {
color: red;
}
</style>
<list id=”demo”></list>
<script src=”./stackoverflow.js”></script>
</body>
</html>

Solution :

You can’t. The list item will lose it’s data after re-render.

You have to add the selected property to the item object in the list component.

Vue.component(‘list-item’, {
props: [‘item’],
methods: {
click() {
this.$emit(‘clicked’);
}
},
template: `
<li :class=”{ selected : item.selected }” @click=”click”>{ item.text }</li>
`
});

var idx = 0;
Vue.component(‘list’, {
data() {
return {
list: [],
}
},
methods: {
additem() {
this.list.push({
text: “li “ + idx++,
selected: false,
});
},
onClick(item) {
item.selected = !item.selected;
},
},
template: `
<div>
<button v-on:click=”additem”>Add</button>
<ul>
<list-item
v-for=”item in list”
:item=”item”
@clicked=”onClick(item)”
:key=”item.text”>
</list-item>
</ul>
</div>
`
});

var demo = new Vue({
el: “#demo”
});

[Vue.js] How to display nested cells in Element UI table?

when using Element UI. there is nested data that I need to display in table. The problem that I can’t understand how to display nested data.

Here is my code:

<el-table :data=”tableData” stripe border>
<el-table-column width=”170” prop=”id”></el-table-column>
<el-table-column width=”170”>
<template slot-scope=”scope”>
<!– –>
</template>
</el-table-column>

</el-table>

data section:

tableData: [
{
“id”:1,
“nested”: [{“name”: “mike”}, {“name”: “piter”}]
},
{
“id”:2,
“nested”: [{“name”: “maria”}, {“name”: “anna”}]
},
]

};

https://jsfiddle.net/3nhb79qc/

to display it’s like:

Solution :

One solution is using span-method in Element UI Table

First, flat the data structure by using computed method:

computed: {
expandData() {
return this.tableData.reduce((a, c) => {
const arr = c.nested.map(item => ({
id: c.id,
name: item.name
}))
a = a.concat(arr)
return a

}, [])
}
},

then the data will become:

[
{
“id”: 1,
“name”: “mike”
},
{
“id”: 1,
“name”: “piter”
},
{
“id”: 2,
“name”: “maria”
},
{
“id”: 2,
“name”: “anna”
}
]

After that define objectSpanMethod and use it in el-table

objectSpanMethod({ row, column, rowIndex, columnIndex }) {
if (columnIndex === 0) {
if (rowIndex % 2 === 0) {
return {
rowspan: 2,
colspan: 1
};
} else {
return {
rowspan: 0,
colspan: 0
};
}
}
}

Demo on jsfiddle

[Vue.js] Conditional Vue component rendering based on ASP Policy assignment

there is an .NET Core backend which is served by a Vue.js frontend.

We have a one-to-many Customer-User relationship, and want to be able to assign one or many users to administrate other users for their customer account.

Using Razor views this was simple as I could simply use

UserManager.IsInRole(“Admin”) { // admin panel button here }…

And serve a clickable button, which would direct to a route authorized using

[Authorize(Roles = “Admin”)].

At run-time, the Razor view simply wouldn’t compile the Admin Panel button if you weren’t in the correct Role, but I’m struggling to achieve similar/identical logic when using a JWT Bearer Token and Policy.

I can authorizes Routes or Actions using Policy assignment:

// Startup.cs
options.AddPolicy(“User”, policy => policy.RequireClaim(JwtConstants.JwtClaimIdentifiers.Rol, JwtConstants.JwtClaims.User));

// Controller.cs
[Authorize(Policy = “User”)]

But I’m struggling to decide how to conditionally mount a vue.js component for the Admin Panel based on the policy assigned to the user.

In the backend everything is correctly authorized, so you can’t navigate or interact with admin controls without being assigned an Admin policy, but rendering this sensibly on the frontend is causing some trouble.

A simple solution would be to simply return an object once a successful signin is completed, such as:

var auth = {
Jwt: ‘xxxxxxxxx’,
Policy: ‘Admin’
}

And then save the Policy prop in LocalStorage, then mount the admin Component based off that, but I’m wondering if there’s a better way that won’t expose the Admin controls to someone who can (trivially) edit LocalStorage?

Solution :

One may add user related info inside the jwt when creating the token.

[Vue.js] Why does my v-if not fire when using modals with Vue?

I’m using v-if to control the display of pages in my vue.js app. the ‘page’ data property keeps track of the current page and is updated by button clicks. This works beautifully until I introduce modals, as now when I open a modal and navigate back a couple of pages (using my app’s navigation buttons) the page fails to display despite the property being updated correctly.

Here’s a simplified example - navigate to page B then C then display Modal 2. Cancel Modal 2, then navigate to Page B and nothing displays (despite the header indicating that the page property is B).

https://jsfiddle.net/fLmq0dxn/1/

I’ve tried this approach with both bootstrap modals and native js modals but the same problem occurs. No errors reported in the console. I thought it might be wrongly nested divs but I’ve checked these and put it through a validator.

I realise that my navigation methods are primitive and that the modals probably should be components, but I’m a newbie to Vue, and as far as I understand it my approach ‘should’ work. Can anyone explain why it doesn’t please?

HTML:

<div id=”app”>

<p>(app.page = {page})</p>
<br/>

<div class=”page” id=”A” v-if=”page==’A’”>
Page A
<br/>
<button v-on:click=”pager(‘B’)”>To B</button>
</div>

<div class=”page” id=”B” v-if=”page==’B’”>
Page B
<br/>
<button v-on:click=”pager(‘C’)”>To C</button>
<button v-on:click=”modalOpen(‘mod1’)”>Modal</button>
</div>

<!– ************ Modal 1 ************************************ –>
<div id=”mod1” class=”mod”>
<div class=”mod-content”>
<span class=”mod-close” v-on:click=”modalClose”>×</span>
<h1>Modal 1</h1>

<button v-on:click=”modalClose” class=”btn btn-secondary”>Cancel</button>
</div>
</div>

<div class=”page” id=”C” v-if=”page==’C’”>
Page C
<br/>
<button v-on:click=”pager(‘B’)”>To B</button>
<button v-on:click=”modalOpen(‘mod2’)”>Modal</button>
</div>

<!– ************ Modal 2 ************************************ –>
<div id=”mod2” class=”mod”>
<div class=”mod-content”>
<span class=”mod-close” v-on:click=”modalClose”>×</span>
<h1>Modal 2</h1>

<button v-on:click=”modalClose” class=”btn btn-secondary”>Cancel</button>
</div>
</div>

</div>

CSS:

/* The Modal (background) */
.mod {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content/Box */
.mod-content {
background-color: #fefefe;
margin: 20% auto;
padding: 20px;
border: 1px solid #888;
border-radius:8px;
width: 90%;
max-width:800px;
}

/* The Close Button */
.mod-close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}

.mod-close:hover,
.mod-close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}

Javascript:

new Vue({
el: “#app”,
data: {
page: “A”
},
methods: {
pager: function(target){
this.page=target;
},
modalOpen: function(modID) {
$(‘#’+ modID).css(‘display’,’block’);
},
modalClose: function(){
$(‘.mod’).css(‘display’,’none’);
}
}
})

Solution :

Combining vue.js with jQuery is risky unfortunately.

In the specific case, it seems like when you try closing the modal, jQuery looks for all elements with “mod” class, but when hiding them, the selection is tampered by vue.js and you end up with incorrect elements being hidden (in the case, the content of the page B). vue.js is not designed to have another library fiddling with the DOM.

You can “easily” achieve the goal using vue.js only. Since you manage the modal by changing their style, you can do something similar with vue.js class and/or style binding.

E.g. you could have a class that overrides the display: none, and you conditionally apply that class based on a data, very similarly as you do for the pages. And you could even probably manage the modal with v-if, exactly like you did with the pages.

Example with conditional class: https://jsfiddle.net/jfx8mbya/

Example with modal managed by v-if:

new Vue({
el: “#app”,
data: {
page: “A”,
modal: null
},
methods: {
pager: function(target) {
this.page = target;
},
modalOpen: function(modID) {
this.modal = modID;
},
modalClose: function() {
this.modal = null;
}
}
})
/* The Modal (background) */

.mod {
/*display: none;*/
/* Hidden by default */
position: fixed;
/* Stay in place */
z-index: 1;
/* Sit on top */
left: 0;
top: 0;
width: 100%;
/* Full width */
height: 100%;
/* Full height */
overflow: auto;
/* Enable scroll if needed */
background-color: rgb(0, 0, 0);
/* Fallback color */
background-color: rgba(0, 0, 0, 0.4);
/* Black w/ opacity */
}

/* Modal Content/Box */

.mod-content {
background-color: #fefefe;
margin: 20% auto;
padding: 20px;
border: 1px solid #888;
border-radius: 8px;
width: 90%;
max-width: 800px;
}

/* The Close Button */

.mod-close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}

.mod-close:hover,
.mod-close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id=”app”>

<p>(app.page = {page})</p>
<br/>

<div class=”page” id=”A” v-if=”page==’A’”>
Page A
<br/>
<button v-on:click=”pager(‘B’)”>To B</button>
</div>

<div class=”page” id=”B” v-if=”page==’B’”>
Page B
<br/>
<button v-on:click=”pager(‘C’)”>To C</button>
<button v-on:click=”modalOpen(‘mod1’)”>Modal</button>
</div>

<!– ************ Modal 1 ************************************ –>
<div id=”mod1” class=”mod” v-if=”modal === ‘mod1’”>
<div class=”mod-content”>
<span class=”mod-close” v-on:click=”modalClose”>×</span>
<h1>Modal 1</h1>

<button v-on:click=”modalClose” class=”btn btn-secondary”>Cancel</button>
</div>
</div>

<div class=”page” id=”C” v-if=”page==’C’”>
Page C
<br/>
<button v-on:click=”pager(‘B’)”>To B</button>
<button v-on:click=”modalOpen(‘mod2’)”>Modal</button>
</div>

<!– ************ Modal 2 ************************************ –>
<div id=”mod2” class=”mod” v-if=”modal === ‘mod2’”>
<div class=”mod-content”>
<span class=”mod-close” v-on:click=”modalClose”>×</span>
<h1>Modal 2</h1>

<button v-on:click=”modalClose” class=”btn btn-secondary”>Cancel</button>
</div>
</div>

</div>

[Vue.js] What's the simplest way to add vue.js typings to an existing typescript file?

I’ve got an existing ASP.NET web site, I’m using Typescript and everything is ticking along nicely.

If I decide to use jQuery I can simply run npm install @types/jQuery, and suddenly jQuery in all is glory is available to me in my .ts file. If to use lodash then npm install @types/lodash and without further ado there is my fully typed lodash.

If however I run npm install @types/vue.js then…. nothing. Any reference to vue.js in my .ts file gets me TS2304 (TS) Cannot find name ‘Vue’.

What’s going on? I thought vue.js was supposed to be one of the most Typescript friendly projects?

Solution :

Check the disclaimer in @types/vue.js https://www.npmjs.com/package/@types/vue

This is a stub types definition for vuejs
(https://github.com/vuejs/vue). vuejs provides its own type
definitions, so you don’t need @types/vue.js installed!

the compiler thinks that @types/vue.js is the right package. But it’s probably causing the bug. You can try to remove it.
If you still can’t get the type, you might need to include node_modules/vue.js into the typing roots