link2466 link2467 link2468 link2469 link2470 link2471 link2472 link2473 link2474 link2475 link2476 link2477 link2478 link2479 link2480 link2481 link2482 link2483 link2484 link2485 link2486 link2487 link2488 link2489 link2490 link2491 link2492 link2493 link2494 link2495 link2496 link2497 link2498 link2499 link2500 link2501 link2502 link2503 link2504 link2505 link2506 link2507 link2508 link2509 link2510 link2511 link2512 link2513 link2514 link2515 link2516 link2517 link2518 link2519 link2520 link2521 link2522 link2523 link2524 link2525 link2526 link2527 link2528 link2529 link2530 link2531 link2532 link2533 link2534 link2535 link2536 link2537 link2538 link2539 link2540 link2541 link2542 link2543 link2544 link2545 link2546 link2547 link2548 link2549 link2550 link2551 link2552 link2553 link2554 link2555 link2556 link2557 link2558 link2559 link2560 link2561 link2562 link2563 link2564 link2565 link2566 link2567 link2568 link2569 link2570 link2571 link2572 link2573 link2574 link2575 link2576 link2577 link2578 link2579 link2580 link2581 link2582 link2583 link2584 link2585 link2586 link2587 link2588 link2589 link2590 link2591 link2592 link2593 link2594 link2595 link2596 link2597 link2598 link2599 link2600 link2601 link2602

[Vue.js] A bunch of bundle files generated due to shared components Subscribe to RSS

when currently migrating a web application based in jQuery to Vue.js. To do it progressive, when creating a different app per each module.

After build the code, there is a common file:

assets/js/vendors.d2c6c799.js

And each app has its own file:

assets/js/admin/dashboard.5c4be0d8.js
assets/js/admin/users.5c4be0d8.js
assets/js/alerts/main.5c4be0d8.js
…..

Up here everything perfect. The problem is that if those applications use same general components, another files are generated like:

assets/js/admin/dashboard~users/users.c3cbae3a.js
assets/js/admin/users~main/users.c3cbae3a.js
assets/js/alerts/dashboard~main/dashboard.c3cbae3a.js
assets/js/alerts/users~main/main.c3cbae3a.js
…..

That is a bit annoying and confused. I would like to each application has their own files, or all shared components in the same js file, but not generate a bunch of js files like in the above example.
Is that possible? Thanks in advance.

Solution :

Since webpack 4 configs automatically split shared modules out into their own chunks.

You can change this behaviour via the optimization.splitChunks configuration property (docs).

To disable the default splitting behaviour altogether set the default and vendor cache groups to false:

optimization: {
splitChunks: {
cacheGroups: {
default: false,
vendor: false,
}
}
}

[Vue.js] Define css pack on build stage for Vue application Subscribe to RSS

there is one single code-base for my vue.js application, but for different end users I need to compile this application with different styles. Let’s say in my public (or assests) folder there is subfolders with css for each single end user (by users in fact I mean a group/organization). So, there is subfolders like:

\public\user1\all.css
\public\user2\all.css
\public\user3\all.css

And when I build my application (npm run build) I need to apply somehow specific styles. Something, like

$ npm run build -css_path \public\user1\all.css

But I don not know, if it is technically possible and if I’m on the right track. Probably, it should be done some other way. So, what is the best practice to apply different styles to vue.js application on the fly (on build or compilation stage)?

Solution :

You can specify environment variable with a particular value, in the case I think it would be userN values.

If css files in the public directory.
Just reference the css file in index.html with environment variable:

<link rel=”stylesheet” type=”text/css” href=”<%= BASE_URL %><%= VUE_APP_MY_VARIABLE %>/all.css”>

And build with VUE_APP_MY_VARIABLE=user1 npm run build
If css files in the assets directory.
Using the same env variable but we should import that css file in the top of the main.js(if you use default project structure):

require(‘./assets/custom/‘ + process.env.VUE_APP_MY_VARIABLE + ‘/all.css’);

or

import(/* webpackMode: “eager” */‘./assets/custom/‘ + process.env.VUE_APP_MY_VARIABLE + ‘/all.css’);

And build with VUE_APP_MY_VARIABLE=user1 npm run build as well.

I also recommend to create .env.local with, for instance, VUE_APP_MY_VARIABLE=user1 to be able to serve the local site and reference some default style to debug the app.

P.S. Check cross-env package which make the life easier with passing env variables. Because my build string is related to bash. With that package it would be cross platform:

cross-env VUE_APP_MY_VARIABLE=user1 npm run build

[Vue.js] Vuejs check if cookie is set without page refresh Subscribe to RSS

What to do with vue.js at the moment is when the user log in the login url would disappear from the navigation.

Currently, I can log in and token cookie is set successfully in the browser. But the problem is while I won’t refresh my page the login url won’t disappear from the navigation bar. Heres some code examples:

Login.vue.js sets the cookie and redirects me to home when I log in:

if(response.status === 200 && response.data.success && response.data.token) {
const token = response.data.token;
this.$cookie.set(‘token’, token);
this.$router.push({name: ‘home’});

Then in Navigation.vue.js I check if the cookie exists:

<li class=”nav-item” v-if=”!cookie”>
<router-link class=”nav-link” to=”login”>Login</router-link>
</li>

data: () => {
return {
cookie: Vue.cookie.get(‘token’)
}
},

So the cookie exists after login but vue.js understands that only after I hit the refresh button in browser or f5. How can I solve this so the login url disappears immediately after login?

This is my axios configuration:

const axiosInstance = axios.create({
baseURL: ‘http://localhost:3000/',
headers: {‘Content-Type’: ‘application/json’},
xsrfCookieName: ‘XSRF-TOKEN’,
xsrfHeaderName: ‘X-XSRF-TOKEN’
});

axiosInstance.interceptors.request.use(
config => {
config.headers[‘Authorization’] = ‘Bearer ‘+ Vue.cookie.get(‘token’);
return config;
},
error => Promise.reject(error)
);

EDIT

Maybe I can achieve something with VUEX?

EDIT 2

So currently this is my solution:
I’ve added VUEX so the token is set like this also:

this.$cookie.set(‘token’, token);
this.$store.state.cookie = this.$cookie.get(‘token’);
this.$router.push({name: ‘home’});

And in my Navbar.vue.js I do this:

computed: {
cookie() {
return this.$store.state.cookie
}
},

and then check like this:

<span v-if=”$cookie.get(‘token’) || cookie”>
Log out
</span>
<span v-else>
<router-link class=”nav-link” to=”login”>Login</router-link>
</span>

$cookie.get(‘token’) || cookie so the cookie is from VUEX which checks it without page refresh but after page refresh VUEX state is gone. So then after page refresh $cookie.get(‘token’) works.

Solution :

Essentially, you want to use some sort of event/signaling mechanism to inform different components about the change in a cookie value. Vuex is one mechanism to do that. Alternately, you can use vue.js instance as an Event bus channel:

STEP 1: Create Event Bus using vue.js in event.js file:

import vue.js from ‘vue’;

export const eventBus = new Vue();

STEP 2: Import it in Login.vue.js and publish an event when cookie is set:

import { eventBus } from ‘./event.js’;

// … Other code
this.$cookie.set(‘token’, token);

// Publish event
eventBus.$emit(‘tokenSet’, token);

STEP 3: Listen to this event in Navigation.vue:

import { eventBus } from ‘./event.js’;

data() {
return {
cookie: Vue.cookie.get(‘token’)
}
},

created() {
eventBus.$on(‘tokenSet’, (token) => this.cookie = token);
}

This way the cookie becomes reactive by updating whenever tokenSet event is fired. With this, you really don’t need to refresh the page and even if refreshed, the initial value of the cookie is read by the data function. In a large-scale application, something like Vuex or Redux is a way to go but the underlying idea is still the same.

For more details refer to this article.

[Vue.js] vue component html does not show up Subscribe to RSS

when having difficulty in getting the component html shown in browser
there is a component called fullName which contains

<template>
<div>
<h3>
{data.firstName} {data.lastName}
</h3>
</div>
</template>

<script>
export default{
name: ‘fullName’,
props:{
data:Object
}
}
</script>

and i pass firstName and lastName as props but when I inspect in chrome the component shows up like this

<fullName data=[object object]></fullName>

instead of

<div>
<h3>Abhishek Singh</h3>
</div>

where I pass Abhishek and Singh as props

can someone help me to debug this or let me know why it is happening

Solution :

Did you register the fullName component in its parent component properly?

[Vue.js] Vue.js - Animate image as cursor moves horizontally Subscribe to RSS

I’ve got a number of images (around 31), The objective is for the page to load with image 1 displayed, then as the cursor runs horizontally, we animate through the images depending on the cursor location.

So far, I’ve got the following method set up

handleMouseMove(evt) {
var e = evt || window.event;
var x = e.offsetX;
this.width = this.$refs.barrelapp.clientWidth;
this.divisions = this.width / 31;
this.position = x;
}

there is this to fire on mousemove over the image element… Which fires and correctly gives me the width of the element, the amount of pixels we should fire each image src, and the current mouse position.

Could anyone shed any light on how I could maybe index this, and run over an array of the 31 images, or something along those lines?

For example, If there is back a width of 1280 and divisions of 41.290322580645, I’d like it to fire an image change on every 41.290 etc pixels.

I’m very new to Vue! So please excuse me if I’ve missed something really obvious!

Ideally, I’d like this to work from left to right, and vice versa!

Thanks guys.

Solution :

you could do something like this…

<script>
export default {
data() {
return {
imageIndex: 0
images: [
// images
]
}
},
computed: {
image() {
return this.images[imageIndex]
// or if you’re using bg image style
return {
‘background-image’: `url(${this.images[imageIndex]})`
}
}
},
methods: {
handleMouseMove(evt) {
const e = evt || window.event;
const x = e.offsetX;
const width = this.$refs.barrelapp.clientWidth;
const divisions = width / this.images.length;
this.imageIndex = Math.floor(x / divisions);
}
},
}
</script>

this assumes you have the images as an array of strings in the data object. You can then use the computed called image to display the relevant image

[Vue.js] Reactivity on axios response data Subscribe to RSS

to set reactivity on my object retrieving by axios request

<div v-for=”plan in techs.plannings”>
<span>{plan.name}</span>
<div v-for=”hour in plan.hours” >
<button @onclick=”changeHour(hour,4)”></button>
</div>
</div>

data : (){
return{
techs : {}
}
},
mounted : (){
axios.get(‘initPlan’).then((res) => {
this.techs = res.data.techs
})
},
methods: {
changeHour(item,4) : {
item.hour = 4
}
}

The axios get request initPlan return an object like this :

[
{
“plannings”: [
{
“id”: 1,
“name”: “June”,
“hours”: {
“2019-06-17”: {
“hour”: 2
},
“2019-06-18”: {
“hour”: 4
}
}
}
]
}
]

When I run this code the techs.plannings.hour are not updated

Solution :

Seems like you’re missing “in” in the v-for on the first line.

Change it to this instead:

<div v-for=”plan in techs.plannings”>

the axios function should also be formatted like this, as an arrow function:

axios.get(‘initPlan’).then((res) => {
this.techs = res.data.techs
})

[Vue.js] Get POST params in Laravel's Controller (sent by javascript/vue) Subscribe to RSS

I’m sending Form data from a vue.js component to Laravel API by POST method.

Laravel return a good response but I’m not able to manage the POST data inside the Laravel controller.

This is the client side:

let body = JSON.stringify({
‘email’: user.email,
‘password’: user.password,
});

fetch(“/login”, {
method: “POST”,
headers: new Headers({
‘Content-Type’: ‘application/x-www-form-urlencoded’,
‘X-CSRF-TOKEN’: user.token, // NOTA: no X_CXRF-TOKEN
body: body
})
})

This is the controller

namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LoginJWTController extends Controller{
public function login(Request $request){
print_r ($request->all());
}
}

But the response (200 OK) is an empty array: array[]

On debug site I see the request header having:

body: {“email”:”me@xxxxx.xx“,”password”:”12345678”}

Why there is no POST data in my Controller? What I’m missing?

Thanks for the help!

Solution :

Currently the body is part of the headers.

Please try this:

let body = JSON.stringify({
‘email’: user.email,
‘password’: user.password,
});

fetch(“/login”, {
method: “POST”,
headers: new Headers({
‘Content-Type’: ‘application/json’,
‘X-CSRF-TOKEN’: user.token, // NOTA: no X_CXRF-TOKEN
}),
body: body
})

Also set the content type to application/json as Salman Zafar pointed out in the comments.

[Vue.js] Vue content rendering outside parent component Subscribe to RSS

When I load a vue.js component inside a @foreach tag it gets rendered first, outside of its parent component.

//view
<div class=”contenido” style=”padding-top:5%”>

<table class=”table”>
<thead class=”thead-dark”>
<tr>
<th class=”col-md-8”>Nombre descripcin general</th>
<th class=”col-md-2”>Actualizar</th>
<th class=”col-md-2”>Consultar</th>
</tr>
</thead>
<tbody>
@foreach($descs as $desc)
<tab-descgen desc-nombre = “{ $desc -> nombre }” desc-id = “{ $desc -> id }”></tab-descgen>
@endforeach
</tbody>

</table>

//vue.js component
<template>
<tr >
<td>{ this.descNombre }</td>
<td><i style=”font-size:30px;” class=”fa fa-edit float-center”></i>
</td>
<td><i style=”font-size:30px;” class=”fa fa-arrow-circle-right
float-center”></i></td>
</tr>
</template>

<script>
export default {
props:[‘descNombre’, ‘descId’],

When this gets rendered the table rows inside the vue.js component will be rendered above the header, and I don’t quite understand why. to know if I’m missing something.

Solution :

Even ignoring all the server-side stuff, this won’t work:

<tbody>
<tab-descgen></tab-descgen>
</tbody>

It’d be fine in a single-file component but if this markup makes it to the browser (as it will in the case) it’ll rip the tab-descgen out of the table before vue.js gets anywhere near it.

You’d need to use is to work around it:

<tbody>
<tr is=”tab-descgen”></tr>
</tbody>

It’s explained here in the docs:

https://vuejs.org/v2/guide/components.html#DOM-Template-Parsing-Caveats

In short, only tr elements are allowed as direct children of tbody, anything else gets pulled out. The workaround is to use a tr and then let vue.js know what you really wanted using is.

Solution 2:

Its because that content is rendered before vue.js loads, i.e. Blade(php) renders the content -> Loads any Javascript(Vue) -> vue.js renders

Solution 3:

You need to pass all the data to the vue.js component and do the loop in there.

[Vue.js] Filter array if it has a specific key value pair Subscribe to RSS

In Vue-JS, when using a computed property and want to filter an array on the basis of key-value pair, this is my array which contains objects as (in data() {}):

menu_content: [
{
title: “Dashboard”,
icon: “dashboard”,
group: false,
},
{
title: “User”,
icon: “account_circle”,
group: true,
sub_menu_items: [
{
title: “Edit”,
sub_group: true,
sub_group_items: [
{
title: “Admin”,
icon: “verified_user”,
},
],
},
]
}
]

Here in this array there is group property which can be false or true, so there is written some code to filter on the basis of this key-value pair as (in computed: {}):

haveSubGroup() {
this.menu_content.forEach(item => {
if (item.group)
return item.sub_menu_items.filter(sub_item => sub_item.sub_group == true);
});
}

If I console.log() the above return statement, it gives me an observable, and if I use { haveSubGroup } in the <template> I don’t see anything!

Solution :

You know you are breaking the loop by using that return statement in the forEach loop, there is following solution for you, hope it will help!

haveSubGroup() {
let temp = [];
this.menu_content.forEach(item => {
if (item.group)
temp.push(item.sub_menu_items.filter(sub_item => sub_item.sub_group == true));
});
return temp[0];
},

Solution 2:

Try this:

haveSubGroup() {
this.menu_content.forEach(item => {
return item.group && item.sub_menu_items.some(sub_item => sub_item.sub_group);
});
}

[Vue.js] VueJS - axios get call does not seem to work Subscribe to RSS

We are using VueJS to build an application, the axios “get” call to fetch the JSON output does not seem to get invoked. Tried to put variables to catch any error but they don’t show anything either. “me.resp” gives the value TBD in the vue.js component, so we know that execution reaches that point.

Please let us know what we might be doing wrong, appreciate the help.

import vue.js from ‘vue’;
import axios from ‘axios’;

export const MY_CONST = ‘Vue.js’;
export let memberList = new Vue({
el: ‘#members’,
data: {
members: null,
resp: null,
error: “No”
},

mounted: function () {
this.getAllMembers();
},

methods: {
getAllMembers: function () {
var me = this;
try {
me.resp = “TBD”;
axios.get(“https://xxxxx.com/services/api.php")
.then(response => (me.resp = response))
.catch(error => (me.error = error));
} catch (error) {
me.error = “Some error”;
}
}
}
});

Solution :

It’s hard to tell from the code why you are not seeing the value being updated. I do however, see a bunch of superfluous code that isn’t doing any work for you. Sometimes a tidy up can bring errors into focus.

The iffrst of these is the usage of var me = this as a way of overcoming scoping issues in the axios callbacks. I see you are using es6 fat arrow functions in these callbacks. What is interesting about these is that they don’t bind their own this context.

As a result, you should be able to do away with the var me = this and just write the callback as response => this.resp = response. While you are at it I would remove the superfluous try catch, since you are already catching in the promise chain. Result would look like:

methods: {
getAllMembers() {
this.resp = “TBD”;
axios.get(“https://etc")
.then(res => this.resp = res)
.catch(err => this.error = err)
}
}

Note that usage of ES6 features is not supported in all browsers and might require transpilation using babel/webpack.

Hope this solves the issue! Otherwise try putting some print statements in the callbacks to see if they are invoked!

Solution 2:

The issue turned out to be of CORS (Cross Origin Resource Sharing). It showed up in the Browser Console output and due to that the call was reaching the server but the response was not being given to the axios get method. I added the appropriate header in the PHP file and now it is fetching data. Thanks to those who took the effort to help.