link548 link549 link550 link551 link552 link553 link554 link555 link556 link557 link558 link559 link560 link561 link562 link563 link564 link565 link566 link567 link568 link569 link570 link571 link572 link573 link574 link575 link576 link577 link578 link579 link580 link581 link582 link583 link584 link585 link586 link587 link588 link589 link590 link591 link592 link593 link594 link595 link596 link597 link598 link599 link600 link601 link602 link603 link604 link605 link606 link607 link608 link609 link610 link611 link612 link613 link614 link615 link616 link617 link618 link619 link620 link621 link622 link623 link624 link625 link626 link627 link628 link629 link630 link631 link632 link633 link634 link635 link636 link637 link638 link639 link640 link641 link642 link643 link644 link645 link646 link647 link648 link649 link650 link651 link652 link653 link654 link655 link656 link657 link658 link659 link660 link661 link662 link663 link664 link665 link666 link667 link668 link669 link670 link671 link672 link673 link674 link675 link676 link677 link678 link679 link680 link681 link682 link683 link684

[Vue.js] Passing an Argument Value to the Data Object as a Key in Vuejs

I’m creating a page that contains 4 different tables for now. All rows in each table will have update and delete buttons. I can make everything work when I code all CRUD functions for each table separately. But what to do is create a function for update action for example, and pass the table name as an argument.

<tr v-for=”asset in assets” :key=”asset.id”>
<td>{asset.id}</td>
<td>{asset.name}</td>
<td>{asset.category.name}</td>
<td>
<a href @click.prevent=”editDialog(asset, ‘asset’)”>Edit</a>
<a href @click.prevent=”deleteThis(asset.id)”>Delete</a>
</td>
</tr>

This is the pop-up window for edit and create an item:

<v-dialog v-model=”dialog”>
<div v-if=”editMode”>
<div v-if=”target_table == ‘asset’”>
<form>…</form>
</div>
</div>
<div v-else>…</div>
</v-dialog>

there is those things in script

export default {
data() {
return {
dialog: false,
editMode: false,
target_table: “”,
assets: {},
asset: new Form({
id: “”,
name: “”,
category: “”,
}),
}
},
methods: {
fetchAssets() {
axios.get(“/api/assets”).then(({ data }) => (this.assets = data));
},
editDialog(data, table) {
this.target_table = table;
this.editMode = true;
this.dialog = true;
this.table.fill(data);
},
},
}

And here is my problem. If you look at the last row of the code, I’m trying to fill a form named “asset” that comes with editDialog(asset, ‘asset’) as its second parameter. But with this syntax, Vuejs goes to data object and look for a “table” as a key instead of “asset” and I’m getting “table is not defined” error. How can I make it work? Thanks.

Solution :

I suggest you to change this.table.fill(data); with this.$data[table].fill(data)

Let me know if it works

[Vue.js] Vue router url could not open page

when using Vue(“vue”: “^2.5.2”) to make a SPA,this is my route(“vue-router”: “^3.0.1”):

routes: [
{
path: ‘/‘,
name: ‘Home’,
component: Home
}]

when I request : http://localhost:8080.It could open the page.But when I tweak the route like this:

routes: [
{
path: ‘/home’,
name: ‘Home’,
component: Home
}]

And I request : http://localhost:8080/home .It could not open the page.Why would this happen ,how to fix it?

Solution :

As stated in the vue.js router docs:

The default mode for vue-router is hash mode - it uses the URL hash to simulate a full URL so that the page won’t be reloaded when the URL changes.

You should find the page at http://localhost:8080/#/home

You can read more about this here

[Vue.js] how to summarize values depending on checked box

when trying to add the numbers together as a summarized value depending on which item is checked to display as total on my checkout page.

there is tried

if ( this.products[0].selected === true ) {
this.summary = this.products[0].price
} else if ( this.products[0].selected === true, this.products[1].selected === true ) {
this.summary = this.products[0].price + this.products[1].price
} else {
this.summary = 0;
}

Obviously no the full statement but it didn’t even work this far.

there is an array of objects containing this

data: {
summary: 0,
products: [
{ name: ‘Hemsida’, price: 290, selected: false },
{ name: ‘Copywriting’, price: 190, selected: false },
{ name: ‘Fotografering’, price: 190, selected: false }
]
}

and when i check my box it turns the linked to !products[0].selected

My latest try was with a switch statement, I might have totally butchered it, since this is my first switch statement on the field :P

priceSummary() {
switch (
(this.products[0].selected,
this.products[1].selected,
this.products[2].selected)
) {
case (true, false, false):
this.summary = this.products[0].price
break
case (true, true, false):
this.summary = this.products[0].price + this.products[1].price
break
case (true, false, true):
this.summary = this.products[0].price + this.products[2].price
break
case (false, false, true):
this.summary = this.products[2].price
break
case (false, true, false):
this.summary = this.products[1].price
break
case (false, false, false):
this.summary = 0
break
case (true, true, true):
this.summary =
this.products[0].price +
this.products[1].price +
this.products[2].price
default:
this.summary = 0
}

It does something, but it doesn’t do what it should :P kind of all over the place. help anyone???

Solution :

The best way is as @Nil says above. But if you want “non-iterable” version without loop you can do it like this:

priceSummary() {
this.summary = 0

if(this.products[0].selected) {
this.summary += this.products[0].price // same as this.summary = this.summary + this.products[0].price
}

if(this.products[1].selected) {
this.summary += this.products[1].price
}

if(this.products[2].selected) {
this.summary += this.products[2].price
}
}

Solution 2:

Somethings like that :

//looping on products
this.product.forEach((prod) => {
//checking if product is selected
if(prod.selected === true){
// if it’s selected, adding its price to the sum
this.summary += prod.price
}
}

?

Solution 3:

If you use array methods, each step can be really easy and readable.
Apart from a few edge cases, a switch statement should not replace a loop.

const model = {
data: {
summary: 0,
products: [
{ name: ‘Hemsida’, price: 290, selected: true },
{ name: ‘Copywriting’, price: 190, selected: true },
{ name: ‘Fotografering’, price: 190, selected: false }
]
}
};
// Create an array of only selected products.
const selected_products = model.data.products.filter( product => product.selected );
// Sum the prices of the selected products.
const price = selected_products.reduce(( sum, product ) => sum + product.price, 0 );

model.data.summary = price;

console.log( model.data.summary );

[Vue.js] Does Vue, by default, provide security for or protects against XSS?

when trying to figure out how to protect,

Angular
Vue
React

against XSS attacks. When I visit the Angular official docs,

https://angular.io/guide/security

, it says:

To systematically block XSS bugs, Angular treats all values as
untrusted by default. When a value is inserted into the DOM from a
template, via property, attribute, style, class binding, or
interpolation, Angular sanitizes and escapes untrusted values.

and also:

Angular sanitizes untrusted values for HTML, styles, and URLs;
sanitizing resource URLs isn’t possible because they contain arbitrary
code. In development mode, Angular prints a console warning when it
has to change a value during sanitization.

and:

Angular recognizes the value as unsafe and automatically sanitizes it,
which removes the tag but keeps safe content such as the
element.

When I go to the React official docs,

https://reactjs.org/docs/introducing-jsx.html#jsx-prevents-injection-attacks

,it says the following:

It is safe to embed user input in JSX:

and:

By default, React DOM escapes any values embedded in JSX before
rendering them. Thus it ensures that you can never inject anything
thats not explicitly written in the application. Everything is
converted to a string before being rendered. This helps prevent XSS
(cross-site-scripting) attacks.

But for Vue, I cannot find anything in their docs about XSS protection, or anything that they could provide by default.

My question: Does Vue, by default, deliver any way of protection against XSS attacks, or would I need to look for a 3rd party solution?

When I Google for this subject I get a lot of blog posts sites and articles refering to, for example, this project to sanitize my HTML:

https://github.com/punkave/sanitize-html

Solution :

There is no built-in sanitizer in vue. As per Evan You’s (Creator of Vue) comment on an issue

built-in sanitizer would add extra bundle weight for a rare use case
(when most use cases of v-html are for trusted content); it is also
trivial to add sanitize-html by setting Vue.prototype.$sanitize =
sanitizeHTML and then do v-html=”$sanitize(html)”.

Check this post : https://github.com/vuejs/vue/issues/6333

[Vue.js] v-for with filter gives error of property or method not defined

I’m using Vue2 with Vuex.
there is a list of posts from https://jsonplaceholder.typicode.com/posts
to show it in descending order.
for that, I created a filter named “desc” in main.js and applied to my component posts.vue.js like this.

<li v-for=”post in posts | desc” :key=”post.id”>

this is my main.js

import vue.js from ‘vue’
import App from ‘./App’
import router from ‘./router’
import { store } from ‘./store/store’

Vue.config.productionTip = false

Vue.filter(‘desc’, function(arr){
if(arr) return arr.reverse();
});

new Vue({
el: ‘#app’,
router,
store,
components: { App },
template: ‘<App/>’
})

it gives me the following error:

[vue.js warn]: Property or method “desc” is not defined on the instance
but referenced during render. Make sure that this property is
reactive, either in the data option, or for class-based components, by
initializing the property. See:
https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

I thought it may cause this error until http get request comes with the response. To troubleshoot this I also tried with static json data but still shows this error.

can any one help me out solving this?

Solution :

Try using slice().reverse() in v-for.

<li v-for=”post in posts.slice().reverse()”>
//do something here
</li>

[Vue.js] VueJS JS-only transition hook requires setTimeout for CSS transition to work

I’m working with pure JS hooks for the <transition-group> element on VueJS, and when quite puzzled on how the enter hook actually works. Based on the documentation, I understand that I will have to call done() to avoid events being called synchronously:

When using JavaScript-only transitions, the done callbacks are required for the enter and leave hooks. Otherwise, the hooks will be called synchronously and the transition will finish immediately.

However, even when I use it, it seems to stop CSS transitions from happening in the entering transition. The only solution I found is to use window.setTimeout to set the style, which I think is a code smell. Here is a quick visual comparison between the code without the timeout, and the one with (the one with the timeout is the desired effect):

Broken enter transition (no transition of the left padding and opacity):

Desired enter transition:

In the example below, when displaying a list using <transition-group> and wanted to use JS-hooks so that I can create staggered paddings on individual list items. It seems to work with the exception that in the enter transition, the CSS transitions on the padding property does not work.

new Vue({
el: ‘#app’,
data: {
items: [
‘Lorem’,
‘Ipsum’,
‘Dolor’,
‘Sit’,
‘Amet’
],
toggle: false
},
computed: {
filteredItems: function() {
if (!this.toggle)
return [];

return this.items;
}
},
methods: {
toggleItems: function() {
this.toggle = !this.toggle;
},
beforeEnter: function(el) {
el.style.paddingLeft = ‘0px’;
el.style.opacity = ‘0’;
},
enter: function(el, done) {
el.style.paddingLeft = `${10 * +el.dataset.index}px`;
el.style.opacity = ‘1’;
done();
},
beforeLeave: function(el) {
el.style.paddingLeft = ‘0px’;
el.style.opacity = ‘0’;
}
}
})
ul {
list-style: none;
margin: 0;
padding: 0;
}

ul li {
transition: all 500ms ease-in-out;
}
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id=”app”>

<button @click=”toggleItems”>
Toggle items
</button>

<transition-group
tag=”ul”
@before-enter=”beforeEnter”
@enter=”enter”
@before-leave=”beforeLeave”>

<li
v-for=”(item, i) in filteredItems”
v-bind:key=”i”
v-bind:data-index=”i”>
{ item }
</li>
</transition-group>
</div>

If you wrap all the logic inside the enter method inside an arbitrary timout, then it works:

enter: function(el, done) {
window.setTimeout(() => {
el.style.paddingLeft = `${10 * +el.dataset.index}px`;
el.style.opacity = ‘1’;
done();
}, 100);
},

And this is where when a little confused: does the enter hook not wait for beforeEnter to complete first? The working snippet is as follow

Solution :

Changing the @enter hook to @after-enter should fix it

there is no clue why the @enter hook isn’t working for this, as looking at the documentation it should but this should at least get rid of the timeout without being a hack

new Vue({
el: ‘#app’,
data: {
items: [
‘Lorem’,
‘Ipsum’,
‘Dolor’,
‘Sit’,
‘Amet’
],
toggle: false
},
computed: {
filteredItems: function() {
if (!this.toggle)
return [];

return this.items;
}
},
methods: {
toggleItems: function() {
this.toggle = !this.toggle;
},
beforeEnter: function(el) {
el.style.paddingLeft = ‘0px’;
el.style.opacity = ‘0’;
},
afterEnter: function(el) {
el.style.paddingLeft = `${10 * +el.dataset.index}px`;
el.style.opacity = ‘1’;
},
beforeLeave: function(el) {
el.style.paddingLeft = ‘0px’;
el.style.opacity = ‘0’;
}
}
})
ul {
list-style: none;
margin: 0;
padding: 0;
}

ul li {
transition: all 500ms ease-in-out;
}

li.v-enter-active {
transition: none
}
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id=”app”>

<button @click=”toggleItems”>
Toggle items
</button>

<transition-group
tag=”ul”
@before-enter=”beforeEnter”
@after-enter=”afterEnter”
@before-leave=”beforeLeave”>
<li v-for=”(item, i) in filteredItems” v-bind:key=”i” v-bind:data-index=”i”>
{ item }
</li>
</transition-group>
</div>

As a side note, if you’re using SCSS or SASS, you can achieve this with that rather than JavaScript

[Vue.js] Vue.js Object is returning but i want to open that Object

This is my code to get the Object which is returning but I cannot open that object to open and see whats in it

var connections = [];
$.each(instance.getAllConnections(), function (idx, connection) {
connections.push({
connectionId: connection.id,
pageSourceId: connection.sourceId,
pageTargetId: connection.targetId,
anchors: $.map(connection.endpoints, function(endpoint) {

return [[endpoint.anchor.x,
endpoint.anchor.y,
endpoint.anchor.getOrientation()[0],
endpoint.anchor.getOrientation()[1],
endpoint.anchor.offsets[0],
endpoint.anchor.offsets[1]
]];
})

});
console.log(util.inspect(connections.endpoints));

});
// console.log(connections);
console.log(util.inspect(connections));

This is what when getting in the Object

Solution :

I got the Object by doing this

var connections = [];
$.each(instance.getAllConnections(), function (idx, connection) {
connections.push({
connectionId: connection.id,
pageSourceId: connection.sourceId,
pageTargetId: connection.targetId,
arrowendpoint1:connection.endpoints[0].anchor.x,
arrowendpoint2:connection.endpoints[0].anchor.y,
arrownendpoint3:connection.endpoints[1].anchor.x,
arrownendpoint4:connection.endpoints[1].anchor.y,

// anchors: $.map(connection.endpoints, function(endpoint) {

// return [[endpoint.anchor.x,
// endpoint.anchor.y,
// endpoint.anchor.getOrientation()[0],
// endpoint.anchor.getOrientation()[1],
// endpoint.anchor.offsets[0],
// endpoint.anchor.offsets[1]
// ]];
// })
});
});
console.log(util.inspect(connections));

[Vue.js] V-model populated in a method not updating the DOM

when newbie in VueJs.(vue.js 2). there is a problem here. there is a table where when dynamically populating data like this.

<tbody>
<tr v-bind:key=”queProduct.value” v-for=”queProduct in queueProducts”>
<td class=”has-text-centered”>
<figure class=”image is-48x48”>
<img :src=”queProduct.image” alt=”Placeholder image”>
</figure>
</td>
<td><span>{queProduct.title}</span></td>
<td class=”has-text-centered”><a class=”has-text-link”>
<span class=”icon is-size-4” @click=”openModalPopup(queProduct.id)”>
<i class=”fa fa-edit” />
</span>
</a>
</td>
<td class=”has-text-centered”><a class=”has-text-link”>
<span class=”icon is-size-4” @click=”openModalPopup(queProduct.id)”>
<img :src=”queProduct.indicatorImg” />
</span>
</a>
</td>
<td class=”has-text-centered”><a class=”delete is-large has-background-link” @click=”removeFromQueue(queProduct.id)”></a></td>
</tr>
</tbody>

methods:{
loadQueue(){

const indicators = store.get(‘productIndicators’);
if(indicators === undefined){
store.set(‘productIndicators’, []);
} else {
this.savedProprogressIndicators = indicators;
}
this.queueProducts.forEach(product => {
product.indicatorImg = indicatorImgBaseUrl +’Level-0.png’;
this.savedProprogressIndicators.forEach(indicator => {
if(indicator.id === product.id){
product.indicatorImg = indicatorImgBaseUrl +indicator.image;
}
})
})
}
}

When I console.log the product, I see the product object being updated with the new value. But the dom isnt getting updated. Like,

this.product looks like this.

{
id: “d6dd8228-e0a6-4cb7-ab83-50ca5a937d45”
image: “https://zuomod.ca/image/cache/catalog/products/2018/Single/medium/50105-1-800x800.jpg"
inQueue: false
indicatorImg: “https://cdn.shopify.com/s/files/1/0003/9252/7936/files/Level-2.png"
saved: false
sku: “50105”
title: “Interstellar Ceiling Lamp”
}

But in the DOM, it looks like this

{
id: “d6dd8228-e0a6-4cb7-ab83-50ca5a937d45”
image: “https://zuomod.ca/image/cache/catalog/products/2018/Single/medium/50105-1-800x800.jpg"
inQueue: false
indicatorImg: “https://cdn.shopify.com/s/files/1/0003/9252/7936/files/Level-0.png"
saved: false
sku: “50105”
title: “Interstellar Ceiling Lamp”
}

Can you please help me resolve this?

Thanks,
Vandanaa

Solution :

As you use Vuex, you should get the products directly from you store like in computed property in the vue.js definition. This will refresh the data directly from store without any action from vue.js side.

{

computed:{
…mapGetters({
queueProducts : ‘queueProducts’
})
}

}

Furthermore, if the are using vuex, try to keep the logic inside the store. You vue.js should only display data.

Hava a look to vuex documentation to know when and where you should use
Getters, Mutations and Actions.

Hope this help.

Solution 2:

this.queueProducts.forEach(product => {



}
this.$forceUpdate(); // Trying to add this code

I guessed the product.indicatorImg was not been watch by Vue, so it will not update the DOM. Trying to add this.$forceUpdate() in the end. It will force vue.js to update DOM.

[Vue.js] Vue js get value from array

Have below code with flights info. Table shows price and flightDuration, but I fail to get airline name from flights array. when new to vue.js js, so would appreciate any help.

UPDATED (still not working):

<tr v-for=”flight in tickets.flights”>
<td>{ flight.airline.name }</td>
</tr>

JSON Data structure:
data: {
tickets: [{
“price”: 100,
“flightDuration”: “75”,
“flights”: [
{
“departureTime”: “12:00”,
“departureDate”: “21 november”,
“arrivalTime”: “13:15”,
“arrivalDate”: “21 november”,
“airline”: {
“code”: “DV”,
“name”: “Scat”
}
}
]
sortKey : ‘flights.departureDate’,
reverse : false,
columns : [
‘flights.departureDate’,
‘flightDuration’
]

https://jsfiddle.net/n7zjpgu5/

Solution :

Below is the correct one and working.

<tr v-for=”ticket in tickets”>
<td v-for=”flight in ticket.flights”>
{ flight.airline.name }
</td>
</tr>

Codepen : https://codepen.io/anon/pen/mozPRW

<tr v-for=”ticket in tickets”>
<td v-for=”flight in ticket.flights”>{ flight.departureDate }</td>
<td v-for=”flight in ticket.flights”>{ ticket.flightDuration }</td>
<td v-for=”flight in ticket.flights”>{ flight.airline.name }</td>
</tr>

Forked the Fiddle and code updated : https://jsfiddle.net/u2skLrz0/

Solution 2:

the problem is that flights is an array. That means there can be more than one airline. You will have to loop again over the flights.

v-for=”flight in product.flights”

If you are sure that there will always be only one flight you can get the name by

{ product.flights[0].airline.name }

Solution 3:

You can access values from array like this:

<td>{ product.flights[0].airline.name }</td>

But if there are more elements in array only the first one will be shown.
For that case you can iterate through array like this:

<tr v-for=”product in list”>
<td>{ product.price }</td>
<td>
<span v-for=”flight in product.flights”>{ flight.airline.name }</span>
</td>
</tr>

Solution 4:

The example will work for you.

<tr v-for = flight in data.flights>
<td>{flight.airline.name}</td>
</tr>

[Vue.js] Get the value of a prop of the before instance Vue

Is possible to save the value of a prop in the data of the component for the next renderizing?
I mean, to update the data component from vue.js and in the new instance get the value of a prop of the before instance

Solution :

As you have stated, re-rendering means just that…rendering again. :)
So the short answer would be no, you can not save prop value within a component and use it after re-rendering.

You say that every minute you are fetching some data that later on you will be doing some logic on. As suggested use Vuex for that, save that data before re-rendering and the use it as you like.

One of many Vue.JS good point is a very well written documentation. You need Vuex so here it is: https://vuex.vuejs.org/