link1507 link1508 link1509 link1510 link1511 link1512 link1513 link1514 link1515 link1516 link1517 link1518 link1519 link1520 link1521 link1522 link1523 link1524 link1525 link1526 link1527 link1528 link1529 link1530 link1531 link1532 link1533 link1534 link1535 link1536 link1537 link1538 link1539 link1540 link1541 link1542 link1543 link1544 link1545 link1546 link1547 link1548 link1549 link1550 link1551 link1552 link1553 link1554 link1555 link1556 link1557 link1558 link1559 link1560 link1561 link1562 link1563 link1564 link1565 link1566 link1567 link1568 link1569 link1570 link1571 link1572 link1573 link1574 link1575 link1576 link1577 link1578 link1579 link1580 link1581 link1582 link1583 link1584 link1585 link1586 link1587 link1588 link1589 link1590 link1591 link1592 link1593 link1594 link1595 link1596 link1597 link1598 link1599 link1600 link1601 link1602 link1603 link1604 link1605 link1606 link1607 link1608 link1609 link1610 link1611 link1612 link1613 link1614 link1615 link1616 link1617 link1618 link1619 link1620 link1621 link1622 link1623 link1624 link1625 link1626 link1627 link1628 link1629 link1630 link1631 link1632 link1633 link1634 link1635 link1636 link1637 link1638 link1639 link1640 link1641 link1642 link1643

[Vue.js] CORS policy blocking request from frontend to backend

when developing an application in vuejs. I need to show some charts on the UI, for this when requesting my backend for the data, but the request is getting blocked due to CORS policy. when using axios to make the request to backend. Here is my chart component which is making the call

<template>
<div class=”filed-against-chart” ref=”chartdiv” id=”filedAgainstChart”>
</div>
</template>

<script>
import axios from ‘axios’;
import * as am4core from “@amcharts/amcharts4/core”;
import * as am4charts from “@amcharts/amcharts4/charts”;
import am4themes_animated from “@amcharts/amcharts4/themes/animated”;
am4core.useTheme(am4themes_animated);

export default {
name: ‘FiledAgainstChart’,
mounted() {
const config = {headers: {‘Access-Control-Allow-Origin’: ‘*‘};
axios
.get(‘http://localhost:3000/ticket/filedagainst', config)
.then(response => this.chart.data = response);

let chart = am4core.create(‘filedAgainstChart’, am4charts.PieChart);
chart.hiddenState.properties.opacity = 0; // this creates initial fade-in

chart.data = [];
chart.radius = am4core.percent(70);
chart.innerRadius = am4core.percent(40);
chart.startAngle = 180;
chart.endAngle = 360;

let series = chart.series.push(new am4charts.PieSeries());
series.dataFields.value = “value”;
series.dataFields.category = “key”;

series.slices.template.cornerRadius = 10;
series.slices.template.innerCornerRadius = 7;
series.slices.template.draggable = true;
series.slices.template.inert = true;
series.alignLabels = false;

series.hiddenState.properties.startAngle = 90;
series.hiddenState.properties.endAngle = 90;

chart.legend = new am4charts.Legend();

}
}
</script>

<style scoped>
.filed-against-chart {
width: 100%;
height: 400px;
}
</style>

there is enabled the CORS middleware in backend.
My app.js file

const createError = require(‘http-errors’);
const express = require(‘express’);
const path = require(‘path’);
const cookieParser = require(‘cookie-parser’);
const logger = require(‘morgan’);
const cors = require(‘cors’);

const ticketRouter = require(‘./routes/ticket’);

const app = express();

// view engine setup
app.set(‘views’, path.join(__dirname, ‘views’));
app.set(‘view engine’, ‘pug’);

app.use(cors());

app.use(logger(‘dev’));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, ‘public’)));

app.use(‘/ticket’, ticketRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get(‘env’) === ‘development’ ? err : {};

// render the error page
res.status(err.status || 500);
res.render(‘error’);
});

module.exports = app;
My router file

Here is my router

const express = require(‘express’);
const router = express.Router();
const ticketTable = require(‘../controllers/ticketTable’);
const cors = require(‘cors’);

router.get(‘/‘, async function (req, res, next) {
const data = await ticketTable.getAllData();
res.send(JSON.stringify(data));
});

router.get(‘/filedagainst’, cors({origin: ‘http://localhost:3000/ticket/filedagainst'}), async function (req, res, next) {
const data = await ticketTable.getFiledAgainstChartData();
res.send(JSON.stringify(data));
});

module.exports = router;

Solution :

You configured the cors module like this:

app.use(cors());

but that only allows for simple requests.

See the documentation for how to support preflighted requests.

Note, that you wouldn’t be making a preflighted request if it wasn’t for this:

const config = {headers: {‘Access-Control-Allow-Origin’: ‘*‘};

custom request headers require a preflight. Of course, Access-Control-Allow-Origin is a response header so it shouldn’t be on the request in the first place. Remove that.

Solution 2:

I searched in Github, there is exists a solution with setting crossdomain in axios
const config = {headers: {‘Access-Control-Allow-Origin’: ‘*‘}; need to replace with { crossdomain: true }

Here is a link to the answer: https://github.com/axios/axios/issues/853#issuecomment-322954804

[Vue.js] How to put the merged css file at the bottom of the head?

I’m using meteor + vue.js , but meteor automatically extracts the css, from the vue.js component within the npm and places it in the head, and causes the css conflict. How can this conflict be avoided?

Meteor 1.8.1
vue.js 2.6.5

There’s a lot of css, on the page head that was originally inside vue.js component. I don’t want that.

A lot of them, causing a lot of css conflicts on the page.

Please help me. Thank’s a lot!

enter image description here
enter image description here

the <meteor-bundled-css /> flag not work

because this tag does not put the merged file at the bottom of the head. I’m so sad..

Solution :

style in head

scss file not found

The correct way

You can create .vueignore files with a RegEx on each line to exclude .vue.js files from the compilation based on their path. If the .vueignore is inside a folder, it only applies to that folder.

For example, you can add the following .vueignore file to the app inorder to ignore .vue.js files in the node_modules folders:

node_modules/

Thanks for @ Akryum :clap:

[Vue.js] how to not rendering back to homepage when in login form?

there is some problem in Single Page application , when I rendering to login form , and when I refresh my page, it return to homepage again, how to block the page to stay in login form when when it is refreshed ?

this is my homepage

<template id=”” v-if=”page.homepage”>
<div class=”container “>
<h1> Homepage </h1>
</div>
</template>

my login:

<template id=”” v-if=”page.login”>
<div class=”container “>
<h1> Login </h1>
</div>
</template>

and my method is

loginButton(){
this.page.homepage = false
this.page.login = true
}

when I try to refresh it, and keep to back to homepage, I really get stuck from yesterday for this :(

Solution :

You can use vue-router and router guards

For example using beforeEach:

router.beforeEach((to, from, next) => {
const authenticated = !!localStorage.getItem(‘token’)

if ([‘login’].includes(to.name) && authenticated) {
next({ path: ‘home’ })
} else if ([‘home’].includes(to.name) && !authenticated) {
next({ path: ‘/login’ })
} else {
next()
}

})

Note that in the above example there is used a stored token to indicate if user is logged or not

[Vue.js] Vue removing event listener on destroy

there is a vue.js directed I use in order to apply a fixed class to the inserted DOM element, in order to do this I also attach an event listener to the window object to run when the user scrolls.

My question is, should I remove this event listener when my element is destroyed? I heard the scroll event can affect performance and I’m not sure if the event listener is automatically destroyed each time I refresh a page (my app is not SPA but a laravel app with vue.js for frontend).

This is my directive:

Vue.directive(‘scroll-apply-class’, {
isLiteral: true,
inserted: (el, binding, vnode) => {

let scrolled = false;
let stickyTop = 300;

setTimeout(function(){

stickyTop = el.offsetTop;

checkPosition();

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

}, 2500);

let checkPosition = function(){
if (window.pageYOffset > stickyTop && window.innerWidth > 765) {
el.classList.add(binding.value)
}
else {
el.classList.remove(binding.value)
}
};

let timeout = setInterval(function() {
if (scrolled) {
scrolled = false;
checkPosition();
}
}, 2500);

}
});

Solution :

If you care about “decency” then yes, do the right thing, remove that listener. But from a pragmatist’s view, maybe not. Since the app is not SPA, each time user click a link and go to other page, that problem is automatically taken cared.

But still, it depends. Is there any chance that in some scenario, this directive is loaded many times on one long-lasting visit to one of the pages? If there is such case, then it’s a good idea to properly unregister the listener. If no, the directive is only loaded once, then you can safely leave it as is.

Solution 2:

You can remove the event listeners on the window in the unbind hook. However, in order to remove the event listeners, you will need to store their callbacks. This can be done by simply storing it as a property of el, e.g. el.scrollCallback:

bind: (el) => {
el.scrollCallback = () => {
el.dataset.scrolled = true;
}
},
unbind: (el) => {
window.removeEventListener(‘scroll’, el.scrollCallback);
},

Then, in the inserted hook, just update the way you store the scrolled boolean. Instead of encapsulating it within the hook, you can store it in the el’s dataset so that it can be accessed by other hooks:

inserted: (el, binding, vnode) => {

// Store data in element directly
el.dataset.scrolled = false;

let stickyTop = 300;

setTimeout(function(){

stickyTop = el.offsetTop;

checkPosition();

window.addEventListener(‘scroll’, el.scrollCallback);

}, 2500);

// REST OF the CODE HERE

// Remember to update all references to `scrolled` to `el.dataset.scrolled`
let timeout = setInterval(function() {
if (el.dataset.scrolled) {
el.dataset.scrolled = false;
checkPosition();
}
}, 2500);

}

[Vue.js] VueJS - usage of v-html attribute not working

In my case, when replacing a link on top of paragraph element using v-html

Please find the code snippet as follows

<p v-html=”websiteHTML”></p>

where websiteHTML contains: <a v-bind:href=”google.com/“>Google</a>

The <p> tag is being rendered with Google but doesn’t have hyperlink to navigate to https://www.google.com/

Could you please help in finding the error?

Solution :

The HTML string you include in the variable should just be HTML, not vue.js template code. When you tried including vue.js template directives, the framework wrote the anchor tag into the DOM with the literal attribute “v-bind:href” instead of the desired “href”:

new Vue({
el: ‘#app’,
data: {
websiteHTMLNo: ‘<a v-bind:href=”https://google.com/">Google</a>', // <– won’t work
websiteHTMLYes: ‘<a href=”https://google.com/">Google</a>' // <– do this instead
},
});
<script src=”https://unpkg.com/vue@latest/dist/vue.js"></script>
<div id=”app”>
<p v-html=”websiteHTMLNo”></p>
<p v-html=”websiteHTMLYes”></p>
</div>

(If you actually do need to inject template code instead of plain HTML, you need to use Vue.compile instead of v-html to parse it.)

[Vue.js] vuetify <v-list-tile> element does not apply color attribute

there is the following list setup but am not able to set a color for a v-list-tile it appears to stay uncolored. This is the template:

<v-container>
<v-flex xs12>
<v-card color=”rgba(75,75,75,1)”>
<v-card-title><h4>Details</h4></v-card-title>
<v-divider></v-divider>
<v-list dense>
<v-list-tile v-for=”(value,key) in testData” dark color=”rgba(85,85,85,1)”>
<v-list-tile-content >{key}</v-list-tile-content>
<v-list-tile-content class=”align-end”>{value}</v-list-tile-content>
</v-list-tile>
</v-list>
</v-card>
</v-flex>
</v-container>

This the result.
Only v-card seems to apply the color attribute
everything below the v-divider does not change it’s color

Solution :

In a v-list-tile the color attribute changes the color of the text only.

If you want to style the background it is easiest to use an inline style.

<v-list-tile
style=”background-color:rgba(85,85,85,1)”

</v-list-tile>

[Vue.js] Call a parent of parent function from child component

there is a simpleMethod function in ChildComponent wich calls a function of the parent component but there is the next situation:

a ViewComponent extends a LayoutComponent and, inside the Child Component. Something like this:

ChildComponent:

<template>
<button @click=”simpleMethod”>smth</button>
</template>
<script>

methods: {
simpleMethod() {
this.$parent.parentFunction()
}
}
</script>

ViewComponent:

<template>
<onepage-layout>
<child-component></child-component>
</onepage-layout>
</template>
<script>

methods: {
parentFunction() {
console.log(‘to fire this function…’)
}
}
</script>

So, when child component fires simpleMethod function, it search the function in OnePageLayout component instead ViewComponent.

I think that i could create a parentFunction inside OnePageLayout just like the one in child component but i imagine that it’s not efficent or a good practice.

Any idea?

Solution :

Child Component:

<template>
<button @click=”simpleMethod”>smth</button>
</template>
<script>

methods: {
simpleMethod() {
this.$emit(‘callParentFunction’); // emit an event to parent
}
}
</script>

ViewComponent:

<template>
<onepage-layout>
<child-component @callParentFunction=”parentFunction”></child-component>
</onepage-layout>
</template>
<script>

methods: {
parentFunction() {
console.log(‘to fire this function…’)
}
}
</script>

You can refer to my another answer.

The communication between parent and child should be using Props down events up, instead of directly call the function thru this.$parent.function(). You should $emit(‘callFunc’) then @callFunc=”function”.

Solution 2:

A good way to accomplish this is using a new vue.js instance as event bus :

window.EventBus = new Vue();

In the child component you can run childFunction:

methods: {

childFunction() {
EventBus.$emit(‘call-parent-function’)
}

}

Then in any component (like parent of parent!) you can listen to the event:

created() {

EventBus.$on(‘call-parent-function’, () => {
this.parentFunction();
})

}

[Vue.js] VueJS doesn't re-render until loop is finished

there is this piece of VueJS code:

new Vue({
el: ‘#app’,
data: {
tiles: [
{ isActive: false },
{ isActive: false },
{ isActive: false },
{ isActive: false },
{ isActive: false }
]

},
methods: {
startWithLoop: function() {
console.log(“startWithLoop”);
for(var i = 0; i < 10000; i++ ) { this.blink() };
},
startWithInterval: function() {
console.log(“startWithInteral”);
setInterval(this.blink);
},
blink: function(){
console.log(“blink”);
var index = Math.floor(Math.random() * this.tiles.length);
this.tiles[index].isActive = !this.tiles[index].isActive;
}
}
})

If I call the method startWithInterval I can see in the view how the tiles are changing state all the time.

If I call the method startWithLoop I don’t see any change in the view until the loop is finished.

Here is the JSFiddle

How can I trigger changes in the view on each step of the loop?

Solution :

No, this is how Javascript eventloop works in browsers (and not only).

You can imagine that Javascript only gets executed in “gaps between moments”, so that the picture of what happens in the browser is a still snapshot of the moment.

Solution 2:

You could write something loop-like that uses setTimeout to let changes be noticed by vue.js and then pushed to the DOM.

beforeDestroy() {
if (this.timeout != null) {
clearTimeout(this.timeout);
this.timeout = null;
}
},
startWithLoop: function() {
console.log(“startWithLoop”);
let i = 0
const iter = () => {
this.blink();
i += 1;
if (i < 10000) {
this.timeout = setTimeout(iter);
}
}
iter();
},

Working fiddle with the changes from above: https://jsfiddle.net/ssorallen/9pqscat1/3/

[Vue.js] Web Components with VueJS

when starting with Web Components with Vuejs and have a basic question. Do we need to include the vue.js js library in the host application for the Web Components to work or is it independent?

Solution :

If you create a Native Web Component without any framework or dependencies then you can use them in Vue, React, Angular or just raw JavaScript.

If you create a vue.js based Web Component then you need vue.js to be able to run it anywhere. If the company switches to React then you will need to run vue.js and React or convert the components to Native or to React.

[Vue.js] Search for giphy url in v-for listing (Vue.js)

there is a list of movie characters which i get from a REST call to my backend using axios. I display them in a bootstrap card for each character. What I’m trying to do is search giphy for the characters name and use the giphy url as img-src for the card.

When I try this and look inside the vue.js devtools, the img-src shows “promise”.

<template>
<div class=”characters”>
<b-container>
<b-card-group columns>
<b-card
v-for=”character in characters”
v-bind:key=”character.id”
:title=”character.name”
:img-src=”getGiphy(character.name)”
img-alt=”Image”
img-top
tag=”article”
style=”max-width: 20rem;”
class=”mb-2”
\>
<b-card-text>
This character is a {character.role}
</b-card-text>
</b-card>
</b-card-group>
</b-container>
</div>
</template>

i try to get the image source with :img-src=”getGiphy(character.name)”

@Component
export default class Characters extends vue.js {
public characters: Character[] = [];
public fields: string[] = [‘name’, ‘role’];

public async getGiphy(name: string) {
const giphyApi: string =
‘//api.giphy.com/v1/gifs/search?api_key=xxxxxxxxxxx&limit=1&q=’;
const response = await axios.get(giphyApi + name);
return response.data.data[0].image_url;
}

private async created() {
const response = await axios.get(‘/api/characters’);
this.characters = await response.data._embedded.characters;
}

Solution :

vue.js can’t resolve promises in properties so you have to do something like this.

Template

<b-card

:img-src=”character.giphyImage”

\>

TS

private async created() {

await Promise.all(this.characters.map(async character => {
character.giphyImage = await this.getGiphy(character.name);
}));
}