link2877 link2878 link2879 link2880 link2881 link2882 link2883 link2884 link2885 link2886 link2887 link2888 link2889 link2890 link2891 link2892 link2893 link2894 link2895 link2896 link2897 link2898 link2899 link2900 link2901 link2902 link2903 link2904 link2905 link2906 link2907 link2908 link2909 link2910 link2911 link2912 link2913 link2914 link2915 link2916 link2917 link2918 link2919 link2920 link2921 link2922 link2923 link2924 link2925 link2926 link2927 link2928 link2929 link2930 link2931 link2932 link2933 link2934 link2935 link2936 link2937 link2938 link2939 link2940 link2941 link2942 link2943 link2944 link2945 link2946 link2947 link2948 link2949 link2950 link2951 link2952 link2953 link2954 link2955 link2956 link2957 link2958 link2959 link2960 link2961 link2962 link2963 link2964 link2965 link2966 link2967 link2968 link2969 link2970 link2971 link2972 link2973 link2974 link2975 link2976 link2977 link2978 link2979 link2980 link2981 link2982 link2983 link2984 link2985 link2986 link2987 link2988 link2989 link2990 link2991 link2992 link2993 link2994 link2995 link2996 link2997 link2998 link2999 link3000 link3001 link3002 link3003 link3004 link3005 link3006 link3007 link3008 link3009 link3010 link3011 link3012 link3013

[Vue.js] Vue data does not display value on console but does display on component

I’m trying to retrieve a global session value and set it to the vue.js variable. The problem is, the id variable is not displaying any value on the console but does display the value on the vue.js component. I’ve checked with the vue.js devtools and the id does contain the correct value.

vue.js Component

<template>
<div class=”container”>
<h1>{id}</h1> // the id does displays the value
</div>
</template>

<script>
export default {
data () {
return {
id:’’,
}
},
created(){
axios.get(‘api/studentlecture’).then(response => this.id = response.data).catch(function(error){console.log(error)
});
console.log(this.id)
},
methods:{

},
mounted() {
console.log(‘Component mounted.’)
}
}

Controller

public function index()
{
$id= session(‘userID’);
return json_encode($id);
}

Solution :

Because the axios call is asynchronous. The JavaScript engine will execute the axios request, and while it is waiting it will continue executing the code.

You are trying to log this.id while it has not yet been assigned. If you want to log the value, you have to put it in the callback of the axios function.

axios.get(‘api/studentlecture’)
.then(response => {
this.id = response.data;
console.log(this.id); // <== Here
})
.catch(function(error){console.log(error)});

Solution 2:

This happens because console.log(this.id) is executed before axios.get() could resolve it’s promise.

There are a few solution for this.

First one is to move console.log() inside then().

created() {
axios.get(‘api/studentlecture’).then(response => {
this.id = response.data;
console.log(this.id);
}).catch(error => {
console.log(error)
});
}

Or you can make use of async/await to wait the promise to resolve

async created() {
try {
// This will wait until promise resolve
const response = await axios.get(‘api/studentlecture’);
this.id = response.data;
console.log(this.id);
} catch(error) {
console.log(error)
}
}

You can learn more about promise here

And more about async/await difference with promise here

Solution 3:

You can try using the following code below:

/*FRONT-END VUE*/

this.axios.get(“https://localhost:8000/api/v1/data").then((response)=>{
this.data=response.data;
console.log(this.data);
if(this.data.success){

}
});
/*BACK-END LARAVEL*/

function getData(){
$result = array(‘success’=>true,’data’=>$data);

return Response()->json($result);
}

[Vue.js] animation of picture doesn't work! Vue.js

The problem is when when using set interval with this top: ${this.imgTop++}px!

const vue.js = require(“@/assets/images/vue.png”);
const bootstrap = require(“@/assets/images/bootstrap.png”);
const bulma = require(“@/assets/images/bulma.png”);

export default {
name: “randImg”,
data() {
return {
images: [
vue,
bootstrap,
bulma
],
addedImage: [],
imgTop: -100,
imgLeft: -100,
imgHeight: 64,
imgWidth: 64,
changeInterval: 750,
selectedImage: ‘’
}
},
created() {
const randomImg = func => setInterval(func, this.changeInterval);
randomImg(this.randomImage);
randomImg(this.addImage);
randomImg(this.randomPosition);
setInterval(this.moveImage,50);
},
methods: {
randomImage() {
const idx = Math.floor(Math.random() * this.images.length);
this.selectedImage = this.images[idx];
},
randomPosition() {
const randomPos = twoSizes => Math.round(Math.random() * twoSizes);
this.imgTop = randomPos(window.innerHeight - this.imgHeight);
this.imgLeft = randomPos(window.innerWidth - this.imgWidth);
},
moveRandomImage() {
const randomImg = func => setInterval(func, this.changeInterval);
randomImg(this.moveImage);
this.randomImage();
},
addImage() {
this.addedImage.push({
style: {
top: `${this.imgTop}px`,
left: `${this.imgLeft}px`,
height: `${this.imgHeight}px`,
width: `${this.imgWidth}px`
},
src: this.selectedImage
});
},
moveImage() {
this.addedImage.style = {
style: {
top: `${this.imgTop++}px`
}
}
}
}
}

don’t understand why but this animataion doesnt work,
basically i will explain how it works:
every second when adding new image with new position from addedImage: [] and this every picture to go down (top++)

additionally this is a template:

<div class=”randImg”>
<img class=”image” :style=”image.style”
:src=”image.src”
v-for=”image in addedImage”>
</div>

Solution :

My guess it’s possible to achieve what you want by adding a watcher on the addedImage array, like every time a new image element is added, you change the style.top of it.

But you shouldn’t use nested setIntervals. I share you this answer explaining why.

I think a simpler and lighter solution is to use css, like creating a @keyframe translation rule:

.drop {
animation: dropDown 1.5s ease-in forwards;
}

@for $i from 1 to 10 {
.drop:nth-child(#{$i}) {
animation-delay: $i * 1.5s;
animation-duration: -1.5s;
}
}

@keyframes dropDown {
0% {
transform: translateY(0);
}
100% {
transform: translateY(600px);
opacity: 0;
}
}

Here’s a live example

Solution 2:

this.addedImage is an array of image, not an image. So, when you do this.addedImage.style, you add a style attribute to the array, but not to the images in the array.

Change moveImage for :

moveImage() {
this.addedImage.forEach(image => {
image.style.top = image.style.top + 1
});
}

[Vue.js] Laravel - how to access the relationship through laravel api

there is a Laravel and Vue.js app that when sending the comments through an API to posts page. Now to get the comments which are for that post through that API and here is what there is tried:

commentController

public function index(){
$comment = Comment::with(‘post’)->get();
return new CommentResource($comment);
}

commentmodel

public function post(){
return $this->belongsTo(Post::class);
}

postmodel

public function comments(){
return $this->hasMany(Comment::class);
}

and here is my Api route

Route::resource(‘comment’,’CommentController’);

and finally here is what I get when I hit

http://localhost:8000/api/comment

which is all of the comments not the comments that belong to the specific post

{
“data”: [{
“id”: 33,
“body”: “a”,
“user_id”: 1,
“user_email”: “a”,
“user_name”: “a”,
“status”: 0,
“post_id”: 9,
“created_at”: “2019-03-25 08:50:55”,
“updated_at”: “2019-03-25 08:50:55”,
“post”: null
}, {
“id”: 32,
“body”: “a”,
“user_id”: 1,
“user_email”: “a”,
“user_name”: “a”,
“status”: 0,
“post_id”: 9,
“created_at”: “2019-03-25 08:50:55”,
“updated_at”: “2019-03-25 08:50:55”,
“post”: null
}, {
“id”: 31,
“body”: “a”,
“user_id”: 1,
“user_email”: “a”,
“user_name”: “a”,
“status”: 0,
“post_id”: 9,
“created_at”: “2019-03-25 08:50:55”,
“updated_at”: “2019-03-25 08:50:55”,
“post”: null
}, {
“id”: 30,
“body”: “a”,
“user_id”: 1,
“user_email”: “a”,
“user_name”: “a”,
“status”: 0,
“post_id”: 1,
“created_at”: “2019-03-25 08:50:55”,
“updated_at”: “2019-03-25 08:50:55”,
“post”: null
}]
}

Any idea how to send just the related comment to the specific post?

Solution :

Try the below code,

I changed the controller index() function to

use NorAm\UserManagement\Http\Requests\Request;

class myController{

public function index(Request $request){
$postId = $request->postId; // this should pass through you API.
$comment = Comment::with(‘post’)->where(‘post_id’,$postId)->get();
return new CommentResource($comment);
}

}

Solution 2:

the relationshipts seem to be correct, should be able to get all the Comments on a json structure with it’s related post nested like:

public function index()
{
return response()->json(Comment::with(‘post’)->get());
}

Maybe you should check the database table structure and foreign keys

Solution 3:

In CommentResource.php you should return the relationship when available

return [

‘post’ => new PostResource($this->whenLoaded(‘post’)),

];

Solution 4:

Am assuming you have post_id in the comments table. So for getting comments of the related to the particular post, you need to pass post_id(for which post you need comment) into the where.
So the query will be:-
Comment::with(‘post)->where(‘post_id’,$postId)->get();
for fetching comments with related post.

Another way with the Post Model:-

And if you are fetching post and you need related comments with the post(the requirement).
then
in the model change the comments method with

public function comments(){
return $this->belongsToMany(Comment::class);
}

Post::with(comments)->get()

with this you can get post as well as comments

[Vue.js] Vue.js transition-group animation doesn't work

there is a slider written as a transition-group component:

<template>
<div class=”carousel-view”>
<transition-group name=”carousel-transition” class=”carousel” tag=”div”>
<div v-for=”(slide, index) in slides”
:key=”index”
class=”slide”>
<div>{ slide.status }</div>
<img :src=”slide.img” />
</div>
</transition-group>
<div class=”carousel-control”>
<button @click=”goToPrevious” class=”button button__main”>Back</button>
<button @click=”goToNext” class=”button button__main”>Next</button>
</div>
</div>
</template>

In my <style> there is this:

<style lang=”scss” scoped>
.carousel {
overflow: hidden;
display: inline;
height: 100%;
width: 900px;
min-width: 200px;
text-align: center;
}
.slide {
display: inline-block;
position: relative;
z-index: 10;
}
.slide:first-of-type, .slide:last-of-type {
opacity: 0.5;
position: absolute;
}
.slide:first-of-type {
right: 50%;
z-index: 5;
}
.slide:first-of-type {
right: 50%;
z-index: 5;
}
.slide:last-of-type {
left: 50%;
z-index: 5;
}
.carousel-transition-move {
transition: transform 1s;
}
</style>

there is two functions in my methods to make my slides move:

goToNext() {
const firstSlide = this.slides.shift();
this.slides = this.slides.concat(firstSlide);
},
goToPrevious() {
const lastSlide = this.slides.pop();
this.slides = [lastSlide].concat(this.slides);
},

All my slides are currently just a hardcoded array in component’s data() with three objects containing an image and some status. Right now I cannot animate slides, nor after clicking on buttons calling those functions, not on the setting an interval. What am I doing wrong?

Solution :

Appearntly, The issue was you were using :key=”index”, whereas vue.js thows an Tip for this in console.

[vue.js tip]: Do not use v-for index as key on children, this is the same as not using keys.

Hence I changed the :key to slide.status and it worked.

Here is the working JsFiddle

Hope this helps!

[Vue.js] How to add array to vue-kanban blocks

I’m implementing vue-kanban component in my web application. There I’d like to display some objects from my database but I need some help to add them to the kanban board.

This is my array with the projects:

props: {
projects: {
type: Array,
required: true,
}
},

And here I’d like to add them to the kanban board, it should be instead of blocks:

data() {
return {
stages: [‘open’, ‘doing’, ‘close’],
blocks: [
{
id: 1,
status: ‘open’,
title: ‘test’,
},
],
};
}

I use that component: https://github.com/BrockReece/vue-kanban

Solution :

See What’s the correct way to pass props as initial data in Vue.js 2?

If the Kanban component is expecting an attribute like :blocks=”[…]“ and nothing is going to happen to the data can you not pass the projects array directly to it? e.g :blocks=”projects”

If no and the data name blocks is a must and the data needs to be mutable then see below.

export default {
name: “YourComponent”,
props: {
projects: {
type: Array,
required: true
}
},
data() {
return {
blocks: this.projects
}
}
}

[Vue.js] Vue router remove params from URL

there is a route set up like below. The idea is that if a user clicks a referral link then the key is stored. In the future if the user navigates to the path /store the same component is used and the referral link will be pulled from storage.

Do I need a route for both /store and /store/:referralKey or is there a way to do this with one route?

const router = new Router({
mode: ‘history’,
routes: [
{
path: ‘/shop/:referralKey’,
name: ‘shop’,
component: () => import(‘./views/Shop’),
meta: {
public: true
}
}
]
})

Solution :

Add ? after the Dynamic params and vue-router will make it optional.

path: ‘/shop/:referralKey?’

Hope this helps!

[Vue.js] How to set background-image url with vue bind

there is a vue.js component that is used based on a items array. The array contains all the relevant information needed in the component. The issues is with setting the background-image url. I only managed to make it work by giving it the whole css syntax instead of just a image url. How can I make it work only with an image url?

<div id=”app”>
<book
v-for=”item in items”
v-bind:item=”item”
\></book>
</div>
<script src=”https://unpkg.com/vue"></script>
<script>
Vue.component(‘book’, {
props: [‘item’],
template: ‘<div class=”book” :class=” item.itemClass “><a :href=”item.link” class=”card”><div class=”thumb” :style=”item.url”></div><article><h1>{ item.titlu }</h1><span>{ item.autor }</span></article></a></div>’
})
var vueApp = new Vue({
el: ‘#app’,
data: {
items: [
{
itemClass: ‘item-1’,
titlu: ‘Title 1’,
autor: ‘Author 1’,
link: ‘www.google.com',
url: ‘background-image: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/210284/flex-1.jpg);',
},
{
itemClass: ‘item-2’,
titlu: ‘Title 2’,
autor: ‘Author 2’,
link: ‘www.google.com',
url: ‘background-image: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/210284/flex-1.jpg)',
},
{
itemClass: ‘item-2’,
titlu: ‘Title 3’,
autor: ‘Author 3’,
link: ‘www.google.com',
url: ‘background-image: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/210284/flex-1.jpg);',
},
]
},
})
</script>

Solution :

Well, In here you need to use inline style binding to apply background-image as you’re directly working with the CSS attribute.

<div v-bind:style=”item.url”></div>

Vue.component(‘book’, {
props: [‘item’],
template: ‘<div class=”book” :style=”item.url” :class=” item.itemClass “><a :href=”item.link” class=”card”><div class=”thumb” :style=”item.url”></div><article><h1>{ item.titlu }</h1><span>{ item.autor }</span></article></a></div>’
})
var vueApp = new Vue({
el: ‘#app’,
data: {
items: [
{
itemClass: ‘item-1’,
titlu: ‘Title 1’,
autor: ‘Author 1’,
link: ‘www.google.com',
url: ‘background-image: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/210284/flex-1.jpg);',
},
{
itemClass: ‘item-2’,
titlu: ‘Title 2’,
autor: ‘Author 2’,
link: ‘www.google.com',
url: ‘background-image: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/210284/flex-1.jpg)',
},
{
itemClass: ‘item-2’,
titlu: ‘Title 3’,
autor: ‘Author 3’,
link: ‘www.google.com',
url: ‘background-image: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/210284/flex-1.jpg);',
},
]
},
})
<script src=”https://unpkg.com/vue"></script>
<div id=”app”>
<book
v-for=”item in items”
v-bind:item=”item”
\></book>
</div>

Hope this helps!

Solution 2:

Inline styles binding requires an object or array of objects, whereas you’re passing a string.

Its form should be:

:style=”{ backgroundImage: ‘url(…)’ }”

Solution 3:

Bind the url to the style attribute

<div class=”book” :class=” item.itemClass “ :style=”item.url”>

Here’s a working example: https://jsfiddle.net/nicolai\_lebek/g6k3v49f/3/

Solution 4:

Use bellow code.

<div id=”app”>
<book v-for=”item in items” v-bind:item=”item”></book>
</div>
<script src=”https://unpkg.com/vue"></script>
<script>
Vue.component(‘book’, {
props: [‘item’],
template: `<div class=”book” :class=” item.itemClass “><a :href=”item.link” class=”card”><div class=”thumb” :style=”{background: ‘url(‘+item.url+’)’}”></div><article><h1>{ item.titlu }</h1><span>{ item.autor }</span></article></a></div>`

})
var vueApp = new Vue({
el: ‘#app’,
data: {
items: [{
itemClass: ‘item-1’,
titlu: ‘Title 1’,
autor: ‘Author 1’,
link: ‘www.google.com',
url: ‘https://s3-us-west-2.amazonaws.com/s.cdpn.io/210284/flex-1.jpg',
},
{
itemClass: ‘item-2’,
titlu: ‘Title 2’,
autor: ‘Author 2’,
link: ‘www.google.com',
url: ‘https://s3-us-west-2.amazonaws.com/s.cdpn.io/210284/flex-1.jpg',
},
{
itemClass: ‘item-2’,
titlu: ‘Title 3’,
autor: ‘Author 3’,
link: ‘www.google.com',
url: ‘https://s3-us-west-2.amazonaws.com/s.cdpn.io/210284/flex-1.jpg',
},
]
},
})
</script>

[Vue.js] Moving Vue component into separate file cannot be found by main app component

I’m trying to work with this Code Sandbox for the NPM Package vue-fixed-header. In the Code Sandbox, the fixed header is in the main App.vue.js file. I’m trying to isolate it to its own file by moving all necessary parts to the HelloWorld.vue.js component inside the component directory. After moving everything, the HelloWorld.vue.js file looks like this:

<template>
<VueFixedHeader
:threshold=”propsData.threshold”
:headerClass=”propsData.headerClass”
:fixedClass=”propsData.fixedClass”
\>
<nav>
<el-menu>
<el-menu-item style=”pointer-events: none;” index=”1”>
Fixed Header
</el-menu-item>
</el-menu>
</nav>
</VueFixedHeader>
</template>

<script>
import VueFixedHeader from “vue-fixed-header”;

export default {
name: ‘fixedHeader’,
components: {
VueFixedHeader,
}
}
</script>

I then try to import this file to be used inside App.vue:

<template>
<div id=”app”>
<fixedHeader /> <– tried importing here

</div>
</template>

<script>
import vue.js from “vue”;
import fixedHeader from ‘./components/HelloWorld’ <– tried importing file here

This doesn’t work though, and Code Sandbox says that fixedHeader is defined but never used.

Solution :

It’s always a good practice to define vue.js components with capitalised camel-casing.

Change the component name of fixedHeader to FixedHeader (can work without this step)
Use it as below:

<template>
<div id=”app”>
<fixed-header/> <– tried importing here

</div>
</template>

<script>
import FixedHeader from ‘./components/HelloWorld’

export default {
components: {
FixedHeader
}
}

Solution 2:

<template>
<div id=”app”>
<fixedHeader /> <– tried importing here

</div>
</template>

<script>
import vue.js from “vue”;
import fixedHeader from ‘./components/HelloWorld’ <– tried importing file here

export default{
components: {
fixedHeader,
}
}
</script>

[Vue.js] Vue Axios local stored token is undefined

In vue.js when building a small Userprofile page. It is build on token-authentication using Axios. When mounting this page the token is undefined.

with login a token is placed in the localStorage.

The Axios Get request is build outside the vue.js component

Api.js

import axios from ‘axios’

export default () => {
return axios.create({
baseURL: `http://localhost:8081/\`
})
}

Get request

import Api from ‘@/services/Api’

let config = {
headers: {
‘Content-Type’: ‘application/json’,
‘Authorization’: localStorage.getItem(‘token’)
}
}

export default {
index () {
return Api().get(‘user/profile’, config)
}
}

Vue

<script>
export default {
data: () => ({
user: {}
}),
mounted () {
this.user = UserProfileService.index
console.log(UserProfileService.config)
}
}
</script>

There are many advices and I tried them all. With tics, with commas etc. Who sees the big picture?

Solution :

Use a request interceptor to set the Authorization header:

// Api.js
export default () => {
const instance = axios.create({
baseURL: `http://localhost:8081/\`
})

instance.interceptors.request.use(function (config) {
const token = localStorage.getItem(‘token’)

if (token) {
config.headers.Authorization = `Bearer ${token}`
}

return config
}, function (error) {
// Do something with request error
return Promise.reject(error)
})

return instance
}

Solution 2:

I added the code from digital drifter, and solved the problem (with help) with changing the mounted function in Vue.

mounted () {
console.log(‘mounted’)
UserProfileService.index()
.then((res) => {
this.user = res.data
})
}

[Vue.js] How to use $nuxt.$loading from axios interceptor

I would like to use $nuxt.$loading https://nuxtjs.org/api/configuration-loading/ outside of vue.js component. I created central js for hitting APIs.

services/api-client.js

import axios from “axios”;
import { state } from ‘../store/modules/sessions’;

const axiosClient = axios.create({
baseURL: process.env.BASE_URL,
headers: {
Accept: ‘application/json’,
‘Content-Type’: ‘application/json’,
‘X-Api-Key’: state().token
}
});

axiosClient.interceptors.request.use(function (config) {
// show nuxt loading here
return config;
}, function (error) {
return Promise.reject(error);
});

axiosClient.interceptors.response.use(function (response) {
// hide nuxt loading here
if (response.data.status.code != 200) {
throw { message: response.data.status.errorDetail };
} else {
return response;
}

}, function (error) {
// hide nuxt loading here
return Promise.reject(error);
});

export default {
all(path) {
return axiosClient.get(path);
},
show(path) {
return this.all(path);
},
create(path, params) {
return axiosClient.post(path, params);
},
update(path, params) {
return axiosClient.put(path, params);
}
};

and from my index.vue.js I’m dispatching the actions which trigger the Api Request.

<template>
<div>
<h1> Welcome </h1>
</div>
</template>

<script>
export default {
created() {
this.$store.dispatch(‘getInsiders’, this);
}
}
</script>

Solution :

Do you really need to declare own axios client?

Standard way how to do this is using nuxt’s axios module and then customize it in the plugin.

nuxt.config.js

modules: [‘@nuxtjs/axios’],
plugins: [‘~/plugins/axios’]

~/plugins/axios

export default ({ $axios, redirect }) => {
$axios.onError(error => {
// do anything you need
})
}

The axios module will manage loading status automatically.
Although you still can disable progress for individual requests

Eg from component/action

await this.$axios.$get(‘/myapi’, { progress: false })