link822 link823 link824 link825 link826 link827 link828 link829 link830 link831 link832 link833 link834 link835 link836 link837 link838 link839 link840 link841 link842 link843 link844 link845 link846 link847 link848 link849 link850 link851 link852 link853 link854 link855 link856 link857 link858 link859 link860 link861 link862 link863 link864 link865 link866 link867 link868 link869 link870 link871 link872 link873 link874 link875 link876 link877 link878 link879 link880 link881 link882 link883 link884 link885 link886 link887 link888 link889 link890 link891 link892 link893 link894 link895 link896 link897 link898 link899 link900 link901 link902 link903 link904 link905 link906 link907 link908 link909 link910 link911 link912 link913 link914 link915 link916 link917 link918 link919 link920 link921 link922 link923 link924 link925 link926 link927 link928 link929 link930 link931 link932 link933 link934 link935 link936 link937 link938 link939 link940 link941 link942 link943 link944 link945 link946 link947 link948 link949 link950 link951 link952 link953 link954 link955 link956 link957 link958

[Vue.js] V-if value condition in table

there is a table with tbody and using Vuejs:

<tbody>
<tr v-for=”(item,i) in data” :key=”i”>
<th scope=”row”></th>
<td>{item.dwg}</td>
<td>{item.name}</td>
<td>{item.ValueOfDay1}</td>
<td>{item.ValueOfDay2}</td>
<td>{item.ValueOfDay3}</td>
</tr>
</tbody>

to use v-if to change the styling of the <td> element:

if item.ValueOfDay1 = 10 –> background-color of <td> is red,
if item.ValueOfDay1 = 10.1 –> background-color of <td> is blue,
if item.ValueOfDay1 = 10.2 –> background-color of <td> is green.

How can I do this?

Solution :

Adding dynamic styling based on condition as below->
:class=”item.ValueOfDay1 == 10 ? ‘bgRed’ : item.ValueOfDay1 == 10.1 ? ‘bgBlue’ : item.ValueOfDay1 == 10.2 ? ‘bgGreen’ : ‘’”

<tbody>
<tr v-for=”(item,i) in data” :key=”i”>
<th scope=”row”></th>
<td>{item.dwg}</td>
<td>{item.name}</td>
<td :class=”item.ValueOfDay1 == 10 ? ‘bgRed’ : item.ValueOfDay1 == 10.1 ? ‘bgBlue’ : item.ValueOfDay1 == 10.2 ? ‘bgGreen’ : ‘’”>{item.ValueOfDay1}</td>
<td :class=”item.ValueOfDay1 == 10 ? ‘bgRed’ : item.ValueOfDay1 == 10.1 ? ‘bgBlue’ : item.ValueOfDay1 == 10.2 ? ‘bgGreen’ : ‘’”>{item.ValueOfDay2}</td>
<td :class=”item.ValueOfDay1 == 10 ? ‘bgRed’ : item.ValueOfDay1 == 10.1 ? ‘bgBlue’ : item.ValueOfDay1 == 10.2 ? ‘bgGreen’ : ‘’”>{item.ValueOfDay3}</td>
</tr>
</tbody>

CSS

.bgRed{
background:red;
}
.bgBlue{
background:blue;
}
.bgGreen{
background:green;
}

Solution 2:

This is resolution for the problem, I hope that help you

https://jsfiddle.net/mathmelo/fjs9x7by/3/#

HTML

<table>
<tbody>

<td :class=”changeBackgroundColor(item.ValueOfDay1)” >{item.ValueOfDay1}</td>

</tr>
</tbody>

Vue

new Vue({
el: ‘#app’,
data: {
data: [
{dwg: 0, name: ‘test’ , ValueOfDay1: 10, ValueOfDay2: 20, ValueOfDay3: 30},
{dwg: 0, name: ‘test2’ , ValueOfDay1: 10.2, ValueOfDay2: 20, ValueOfDay3: 30},
{dwg: 0, name: ‘test3’ , ValueOfDay1: 10.1, ValueOfDay2: 20, ValueOfDay3: 30}

]
},
methods: {
changeBackgroundColor(valueOfDay) {
//Get the decimal part of the number
decimals = valueOfDay - Math.floor(valueOfDay);

switch(decimals.toFixed(1)){
case ‘0.0’ : return ‘red’
case ‘0.1’ : return ‘blue’
case ‘0.2’ : return ‘green’

}
}
}
});

And CSS

.red {
background-color: red;
}

.blue {
background-color: blue;
}

.green {
background-color: green;
}

[Vue.js] Vue router detect click on router-link-exact-active

I’ve seen this question multiple times, but without a good response

there is a topmenu with links and to trigger a function when I click the link of the page that I’m on right now

How do I achieve this?

Remember the in-component guards wont trigger because the route does not change

Solution :

You would want to trigger a function on all links and trigger the navigate from in there passed by a param.

Then check if the current page URL matches the passed param.

E.g.

if (this.$router.currentRoute == ‘param passed’) {
return someOtherFucntion();
}

return this.$router.push(‘param passed’);

Its called programmatic navigation you can see more here.

https://router.vuejs.org/guide/essentials/navigation.html#programmatic-navigation

Solution 2:

I believe I found a more elegant solution
I made a wrapper for links

<template>
<a :href=”resolvedRoute.route.fullPath” :class=”{ ‘is-active’: resolvedRoute.route.name == $route.name }” @click.prevent=”clicked”>
<slot></slot>
</a>
</template>

<script>
import EventBus from ‘@/event-bus’

export default {
name: ‘menu-link’,
props: {
to: {
type: Object,
default: {}
}
},
computed: {
isExactActive(){
return this.$route.fullPath == this.resolvedRoute.route.fullPath
},
resolvedRoute(){
return this.$router.resolve(this.to)
}
},
methods: {
clicked(){
if(this.isExactActive)
return EventBus.$emit(‘page-reload’, this.resolvedRoute.route)

this.$router.push(this.to)
}
}
}
</script>

Then a simple mixin

import EventBus from ‘@/event-bus’

export default {
mounted(){
EventBus.$on(‘page-reload’, this.checkPageReload)
},
beforeDestroy(){
EventBus.$off(‘page-reload’, this.checkPageReload)
},
methods: {
checkPageReload(route){
if(route.name == this.$options.name && this.pageReload){
EventBus.$emit(‘page-loading’, true)
this.pageReload(route)
}
}
}
}

I believe this is the optimal solution. I’ll just have to replace router-link with menu-link

[Vue.js] How merge mutil object in array with lodash?

there is a bit of problems with my code :

[
{
“key”: 0,
“server”: 0
},
{
“key”: 0,
“server”: 1
},
{
“key”: 1,
“server”: 0
}
]

how i can result to :

[
{ key: 0 , server:[0,1] },
{ key: 1 , server:[0] }
]

I’m using _.groupBy but it does not return results as expected.
How merge mutil object in array with lodash?

Solution :

One solution would be to use a combination of groupBy, map, and mergeWith.

So first, you group the items by key, so in this example it will return an object with 0 and 1 as the keys which will contain the grouped items.

Then you use .map to iterate through the returned object and get the grouped values.

Finally, you use .mergeWith with a customizer function which you can use to customize the how the values of the server key is merged.

const servers = [{
“key”: 0,
“server”: 0
},
{
“key”: 0,
“server”: 1
},
{
“key”: 1,
“server”: 0
}
];

function customizer(objValue, srcValue, key, fourth) {
if (key === ‘server’) {
if (!_.isArray(objValue)) objValue = [objValue];
return objValue.concat(srcValue);
}
}

let test = _(servers)
.groupBy(‘key’)
.map((values, key) => {
if (values.length === 1) {
values[0].server = [values[0].server];
return values[0];
}
return _.mergeWith(…values, customizer);
})
.value();

console.log(test);
<script src=”https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Solution 2:

new Vue({
el: “#app”,
data: {
needMergedArray: [
{
key: 0,
server: 0
},
{
key: 0,
server: 1
},
{
key: 1,
server: 0
}
],
},
methods: {
mergeObject() {
let merged = [];
this.needMergedArray.map(item => {
let found = false;
merged.map(element => {
if(item.key === element.key) {
found = true;
if(!element.server) {
//const myserver = [item.server];
element.server =[item.server];
} else {
element.server.push(item.server);
}
}
});
if(!found) {
const myserver = [item.server];
merged.push({key: item.key, server: myserver});
}
found = false;
});
return merged;
}
}
})

Solution 3:

// one loop solution: https://jsfiddle.net/haianhnc/2mhsquad/78

mergeObject() {
let merged = {};
this.needMergedArray.map(item => {
merged = {…merged, [item.key]: {key: [item.key], server: (merged[item.key] && merged[item.key].server || []).concat(item.server)};
});
return Object.values(merged);
}
}

Solution 4:

Haven’t tested yet

arr.reduce(function(acc,value){
const isExists = acc.findIndex(({key})=>key===value.key)
if(!isExists){
acc.push(value)
} else {
let servers = acc[isExists].server
if(!Array.isArray(servers))
servers = [servers]
servers.push(value.server)
servers = _.uniq(servers)
acc[isExists].server = servers
}
return acc
},[])

[Vue.js] How to write async code inside vuex action object?

there is Rest api for my vue.js app, and want to know is there any other way to write async code using vuex?

My code looks like this

//store.js

const actions = {
async GET_CLAN_MEMBERS({commit},id){
let token = users.getters.getToken;
return await axios.post(config.api + ‘clans/‘ + id,{token})
}
};

//Component.vue

created (){
this.$store.dispatch(‘GET_CLAN_MEMBERS’,this.$route.params.id).then((res) =>
{
this.members = res.data;
})
},

Now it’s working but I don’t know is it the best place or practice write it inside store.js file.
Thanks in advance.

Solution :

me too, got this question over my head and indeed store can consume rest api’s inside their actions.

This is why vuex support modules, to avoid too big store files.

I did a few experimentation here (missiang the modularization but works as a good example), and the official documentation itself says to call the async operations inside actions. So, axios/rest inside actions are the recommended way.

Solution 2:

standard practice : actions always used as setter , so after api call back response you should call mutation to change state based on response data, and getters used as getter(state data retrieval)

So you should follow below flowchart for standard practice:

For more info read here

[Vue.js] Unable to align div content

when developing an application using Vue.js and Bootstrap. when looking to develop a folder to look like this:

But, when unable to align the contents to make sure that it looks like in the above picture.

The picture currently looks like this:

Here is the code:

<div class=”col-xl-3 col-md-6”>
<stats-card>
<div slot=”header” class=”folderRectangle”>
<div class=”row”>
<div class=”col-3”>
<div class=”clearfix”>
<i class=”material-icons” id=”folder-image”>folder</i>
</div>
</div>
<div class=”col-9”>
<div class=”clearfix” style=”position: relative”>
<div>
<p style=”text-align: left”>Folder Name</p>
</div>
<div>
<p style=”text-align:left”>20 files</p>
</div>
</div>
</div>
</div>
</div>
</stats-card>
</div>

What wrong am I doing? How do I make sure that the folder icon aligns to the top and text floats to the center?

Solution :

Instead of using .row and .col-*, you can use the media object already available in Bootstrap to produce this layout.

/* demo only */

.media {
border: 1px solid #ddd;
padding: 1.5rem;
margin: 1rem;
}

img {
max-width: 25px;
}

.media-body {
font-size: 0.75rem;
}
<link rel=”stylesheet” href=”https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity=”sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS” crossorigin=”anonymous”>

<div class=”media”>
<img class=”mr-3” src=”https://png.pngtree.com/element\_our/png/20181213/folder-vector-icon-png\_267455.jpg" alt=”Generic placeholder image”>
<div class=”media-body”>
<h6 class=”mt-0 mb-1”>Folder name</h6>
<div>20 files</div>
</div>
</div>

Solution 2:

The best possible way to achieve what you are trying is to use CSS Flex property.

Just give display flex to the parent (col-9) in the case.
Provide align items to be center.
and at last flex alignment to row.

this will make you achieve the above design

You can read about CSS flexbox more here
https://www.w3schools.com/css/css3\_flexbox.asp

[Vue.js] Access php array inside vue.js template

I’m trying to learn Laravel and vue.js and stumbeled upon a problem. there is this Laravel model which contains a php method that fetches data from a database and puts into objects which are then put into an array. I would then like to access this array inside a vue.js component, but I dont know how when supposed to do that.

My Laravel model fetches data from the database and puts into objects in an array
I can print out the array, without using vue, from my index.blade.php like this:

@foreach ($data[‘hosts’] as $hostsKey => $hostsValue)
<ul>
@foreach ($hostsValue as $hostKey => $hostValue)
<li>{!!$hostKey!!}: {!!$hostValue!!}</li>
@endforeach
</ul>
@endforeach

Is it possible to access it inside my vue.js component by putting this in my index.blade.php instead of the above example?

<div id=”app”>
<hosts></hosts>
</div>

with the app.js looking something like this:

Vue.component(‘host’, require(‘./components/host.vue’).default);

const app = new Vue({
el: ‘#app’
});

and my host.vue.js looking like this:

<template>
<div>
{ hostData }
</div>
</template>

<script>
export default {
data(){
return{
hostData: /* MY PHP VARIABLE HERE */
}
}
}
</script>

Started out trying vue.js today, so please don’t be too hard on me.

Solution :

You could modify the component to receive an array as a prop like :

<template>
<div>
{ hostData }
</div>
</template>

<script>
export default {
props:[‘hostData’],
data(){
return{

}
}
}
</script>

in blade template pass the $data[‘hosts’] through host-data prop :

<div id=”app”>
<host :host-data=”@json($data[‘hosts’])”></host>
</div>

[Vue.js] Api response is null when consumed, with django and vue

Im using my api from the rest framework, when I got to the URL from the api it shows’s it correct. But when I consume it the response seems to be null.
Im hosting both project (front vuejs and back django) in diferents ports (8080 and 8000, respectively). CORS are allowed.

I’ve tried with another tools like fetch or jquery and seems to be the same.

Js:

export class APIService {
contructor() {}

get_user_id(){
const url = `http://localhost:8000/api/v1/user-id/\`;
return axios.get(url).then(function (response) {
console.log(response); // For testing
return response.data;
});
}
}

Django api view, for that url:

class UserIdLoggedView(APIView):
def get(self, request):
user = request.user
return Response({
‘id’: user.id,
})

For this case I didn’t need a serializer.

This is how the django rest shows it:

{ HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
“id”: 1
}

And this is the output of the response from the console (just the data part)

data:
id: null

Instead of return id=1 as expected it return null.

Solution :

why are you using two return statements in get_user_id? You hit the first return statement and it doesn’t wait for the promise to be fulfilled. Basically, you send the get request but don’t wait for the response. Also, I would recommend creating a base instance of axios as a vue.js plugin.

[Vue.js] How to make ui such that each web component in ui should fetch data from different api using vuejs

how to make ui such that each web component in ui should fetch data from different api using vuejs. Multiple microservices should have one ui in which each web component gets data from different microservices.

Solution :

it is not a problem and vue.js is a best tool for such a things.

lets say you have main Component that name App
and inside you have few components named, Users, News, Posts like this:

<template>
<Users></Users>
<News></News>
<Posts></Posts>
</template>

and we take Posts for example.

<template>
<div>
<div class=”post” v-for=”post in posts”>
<a :href=”post.link”>{ post.title }</a>
</div>
</div>
</template>

<script>
export default {
mounted() {
setInterval(function () {
// here you are doing the Ajax request, axios, jQuery etc.
// and updating this.posts
this.posts = server.posts;
}, 5000);
},
data() {
return {
posts: [] // empty for now.
}
}

}
</script>

after you do this, each component is responsible for its own ajax(s) and will update the data so it reflect in the App Component.

[Vue.js] How to ignore plugin on Vue CLI3 in vue.congif.js

I’m using vue.js cli3, and want to ignore moment.js plugin with webpack. This is the rule, but on vue.confing.js it gives an error no matter how I change it.

plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
],

Solution :

You appear to be trying to use the deprecated constructor. Try this instead and don’t forget to import webpack into the script…

const webpack = require(‘webpack’)

module.exports = {
configureWebpack: {
plugins: [
new webpack.IgnorePlugin({
resourceRegExp: /^\.\/locale$/,
contextRegExp: /moment$/
})
]
}
}

[Vue.js] How to call mixin function in middleware

How can I call mixin function in middleware with NUXT.js?

when trying to do this:

export default function(context) {
// init auth token from the local store or cookies
context.initAuth(context.req)

if (!context.store.getters[‘sessionStorage/isAuthenticated’]) {
context.redirect(“/login”)
}
}

where initAuth() function is located in the plugins/auth.js mixin file

Solution :

You can’t call mixin in middleware, because mixin is something related to vue-component instanse.
Did you mean you want to call a function? Then you doing it right, except you should inject the function into the context.