# [Vue.js] v-if using table row field and date range

I’m trying to highlight a <td> based on that field’s date range from today’s date.

I’ve been trying to use current <td> date value less than Date.now() - #(number of days) to determine whether to highlight the <td> (green, yellow, or red) but not having any success with how I’m doing so.

<td v-if=”props.item.date < Date.now() - 2”>
<v-icon small style=”color:green;”>fiber_manual_record</v-icon>{ props.item.date }
</td>
<td v-else-if=”props.item.date < Date.now() - 7”>
<v-icon small style=”color:yellow;”>fiber_manual_record</v-icon>{ props.item.date }
</td>
<td v-else>
<v-icon small style=”color:red;”>fiber_manual_record</v-icon>{ props.item.date }
</td>

I’d like to think I’m close to the solution but I may not be doing it the appropriate way. Any help would be greatly appreciated.

UPDATE 2

<td v-if=”Date.parse(props.item.date) > Date.now()”>
<v-icon small class=”greenDate”>fiber_manual_record</v-icon>{ props.item.date_sent }
</td>
<td v-else-if=”Date.parse(props.item.date) < Date.now()”>
<v-icon small class=”yellowDate”>fiber_manual_record</v-icon>{ props.item.date_sent }
</td>
<td v-else”>
<v-icon small class=”redDate”>fiber_manual_record</v-icon>{ props.item.date_sent }
</td>

Tried this just to test and see if anything is even recognized the conditions and it doesnt seem like it. Always hits the last condition (red). Maybe its not like props.item.date formatted mm/dd/yyyy. I also realized my conditions in the original example would conflict since there is both a less than 2 days and 7 days, but no condition for also greater than 2 days under 7 days condition

### Solution :

The Date.now() method returns the number of milliseconds

So if you want to reduce somedays. you have to covert days to milliseconds and then minus. 1 day = 1000 * 60 * 60 * 24 * 1 milliseconds

The Date.parse() method parses a string representation of a date, and returns the number of milliseconds

Convert props.item.date to milliseconds using Date.parse

for example change code like below

<td v-if=”Date.parse(props.item.date) < Date.now() - (2 * 1000 * 60 * 60 * 24)”>
<v-icon small style=”color:green;”>fiber_manual_record</v-icon>{ props.item.date }
</td>
<td v-else-if=”Date.parse(props.item.date) < Date.now() - (7 * 1000 * 60 * 60 * 24)”>
<v-icon small style=”color:yellow;”>fiber_manual_record</v-icon>{ props.item.date }
</td>
<td v-else>
<v-icon small style=”color:red;”>fiber_manual_record</v-icon>{ props.item.date }
</td>

# [Vue.js] Making only one module persistent with vuex-persistedstate

I need to use vuex-persistedstate to make only one of my modules to persists state through refresh of the page.

Right now, it doesn’t work when I use plugins: [createPersistedState()] only inside the user module.

plugins: [createPersistedState()] works only when I use it inside the store’s index.js but it make all modules persistent which is not what I want.

Please, is there a way how to configure vuex-persistedstate to work only with one module?

index.js

//import createPersistedState from ‘vuex-persistedstate’
import vue.js from ‘vue’
import Vuex from ‘vuex’
import user from ‘./modules/user’
import workout from ‘./modules/workout’

Vue.use(Vuex)

export default new Vuex.Store({
state: {

},
getters: {

},
mutations: {

},
actions: {

},
modules: {
user,
workout
},
//This makes all store modules persist through page refresh
//plugins: [createPersistedState()]
})

user.js

import { USER } from ‘../mutation-types’
import createPersistedState from ‘vuex-persistedstate’

export default {
namespaced: true,

state: {
darkMode: true
},

getters: {
getDarkMode: state => () => state.darkMode
},

actions: {
toggleDarkMode: ({commit}) => commit(USER.TOGGLE_DARKMODE)
}

mutations: {
[USER.TOGGLE_DARKMODE]: (state) => state.darkMode = !state.darkMode
},
//This doesn’t work
plugins: [createPersistedState()]
}

### Solution :

Looking at the API docs, you will need to configure the plugin to only persist a certain subset of the store.

export default new Vuex.Store({
// …
plugins: [
createPersistedState({
paths: [‘user’],
}),
],
});

From the docs above:

paths <Array>: An array of any paths to partially persist the state. If no paths are given, the complete state is persisted. Paths must be specified using dot notation. If using modules, include the module name. eg: “auth.user” (default: [])

# [Vue.js] Carrierwave upload an image from vue front to rails api

when not sure how to make the axios post for the image.

This is what my json object looks like.

{
“id”:20,
“title”:”pineapple”,
“text”:”pineapple”,
“date”:null,
“created_at”:”2019-03-23T01:42:48.142Z”,
“updated_at”:”2019-03-23T01:42:48.142Z”,
“image”:{
“url”:null
}
}

This is my image input from the vue.js form.

<input type=”file”
id=”file”
ref=”myFiles”
class=”custom-file-input”
@change=”takeFile”
multiple>

Here is me trying to make sense of it.

export default {
data() {
return {
blog: {
title: ‘’,
content: ‘’,
}
}
},
methods: {
submitArticle(blog) {
axios.post(‘http://localhost:3000/articles', {
title: blog.title,
text: blog.content,
image: {
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
},
takeFile(event) {
console.log(this.$refs.myFiles.files); this.blog.link = this.$refs.myFiles.files
}
}
}

Here is a link to the file in my repo.

### Solution :

First this.$refs.myFiles.files returns an array of files. Change the method like this to set the file to blog.link: takeFile(event) { this.blog.link = this.$refs.myFiles.files[0]
}

Now to send file in the post request, you should use FormData:

submitArticle(blog) {
let formData = new FormData()
formData.append(“article[title]“, blog.title)
formData.append(“article[text]“, blog.content)
axios.post(‘http://localhost:3000/articles', formData, {
‘Content-Type’: ‘application/json’
}
}).then(function (response) {
console.log(response)
}).catch(function (error) {
console.log(error)
})
},

# [Vue.js] Vue JS Difference of data() { return {} } vs data () => ({ })FixReason

I’m curious both of this data function, is there any difference between this two.

I usually saw is

data () {
return {
obj
}
}

And ES6 “fat arrow” which I typically used

data:()=>({
obj
})

### Solution :

No difference in the specific example, but there is a very important difference between those two notations, specially when it comes to Vue.js: the this won’t reflect the vue.js instance in arrow functions.

So if you ever have something like:

export default {
props: [‘stuffProp’],
data: () => ({
myData: ‘someData’,
myStuff: this.stuffProp
})
}

It won’t work as you expect. The this.stuffProp won’t get the stuffProp prop’s value (see below for more on the reason why).

Fix

Change the arrow function to, either (ES6/EcmaScript 2015 notation):

export default {
props: [‘stuffProp’],
data() { // <== changed this line
return {
myData: ‘someData’,
myStuff: this.stuffProp
}
}
}

Or to (regular, ES5 and before, notation):

export default {
props: [‘stuffProp’],
data: function() { // <== changed this line
return {
myData: ‘someData’,
myStuff: this.stuffProp
}
}
}

Reason

Don’t use arrow functions (() => {}) when declaring vue.js methods. They pick up the this from the current scope (possibly window), and will not reflect the vue.js instance.

From the API Docs:

Note that you should not use an arrow function with the data property (e.g. data: () => { return { a: this.myProp }). The reason is arrow functions bind the parent context, so this will not be the vue.js instance as you expect and this.myProp will be undefined.

# [Vue.js] Vuetify Navigation Drawer Drag To Resize

So there is gotten it to where the the ‘drag to resize’ works - it just feels a little laggy… does anyone know why this may be, and how to fix it?

there is tried forcing a refresh using vm.$forceUpdate() but that did not seem to do anything.. The CodePen can be found here. ### Solution : Thats because of transition effect on navigation drawer. set transition to initial at mouse down, then release that on mouse up. at mousedown add el.style.transition =’initial’; at mouseup add el.style.transition =’’; # [Vue.js] Abnormal behavior of Select in Vue.js there is a primitive vue.js widget, which consists of two pages. In each page you can select dummy options from dropdown (which change value1 and value2 variables accordingly) The problem is when I move from “stepOne” to “stepTwo”, for some reason the value of value2 becomes undefined unexpectedly (even though there is no logical connection between value1 and value2, nor step variable). Ideally, after the first step, in second step it should automatically select “option 1”, as the value equals to value2=1 I wonder why undefined is assigned to value2, and how can I prevent the given behavior Here is my sample code, that contains this weird behavior: <div> <div id=”app”> <div v-if=”step === steps.stepOne”> <p>This is step One</p> <select v-model=”value1”> <option v-for=”item in array1” :value=”item.value”>{ item.name }</option> </select> <button @click=”changeStep()”>Next</button> </div> <div v-if=”step === steps.stepTwo”> <p>This is step Two</p> <select v-model=”value2”> <option value=”2”>option 2</option> <option value=”0”>option 0</option> <option value=”1”>option 1</option> </select> </div> value1: {value1} <br> value2: {value2} </div> </div> <script src=”https://cdn.jsdelivr.net/npm/vue"></script> <script> var steps = { stepOne: 1, stepTwo: 2, }; var app = new Vue({ el: ‘#app’, data: { step: steps.stepOne, value1: ‘b’, value2: 1, array1: [ { name: ‘option a’, value: ‘a’, }, { name: ‘option b’, value: ‘b’, }, ] }, methods: { changeStep() { this.step = steps.stepTwo; } }, watch: { value1: function(newValue) { console.log(“value1: “ + newValue); }, value2: function(newValue) { console.log(“value2: “ + newValue); } }, }); </script> ### Solution : there is no idea about how vue.js works, but I’ve tried putting a : before the value attribute and it started working! <div> <div id=”app”> <div v-if=”step === steps.stepOne”> <p>This is step One</p> <select v-model=”value1”> <option v-for=”item in array1” :value=”item.value”>{ item.name }</option> </select> <button @click=”changeStep()”>Next</button> </div> <div v-if=”step === steps.stepTwo”> <p>This is step Two</p> <select v-model=”value2”> <option :value=”2”>option 2</option> <option :value=”0”>option 0</option> <option :value=”1”>option 1</option> </select> </div> value1: {value1} <br> value2: {value2} </div> </div> <script src=”https://cdn.jsdelivr.net/npm/vue"></script> <script> var steps = { stepOne: 1, stepTwo: 2, }; var app = new Vue({ el: ‘#app’, data: { step: steps.stepOne, value1: ‘b’, value2: 1, array1: [ { name: ‘option a’, value: ‘a’, }, { name: ‘option b’, value: ‘b’, }, ] }, methods: { changeStep() { this.step = steps.stepTwo; } }, watch: { value1: function(newValue) { console.log(“value1: “ + newValue); }, value2: function(newValue) { console.log(“value2: “ + newValue); } }, }); </script> # [Vue.js] Convert String to Object Key Name I’m sending different objects to a component outside, and component data varies depending on objects. I’m getting the names with the Object.key function because the keywords I send have different key. Then to sort by the key. For this I need to define the name I received with Object.key function. How can I do it? upSortTable(items, val) { //items = Object, //val = index let Keys = Object.keys(items[0]); // [“item_id”,”item_title”] let keyname = Keys[val]; //item_id String value //want to use in sort function as b.item_id return items.sort(function(a, b) { return b.keyname - a.keyname; }); }, ### Solution : You’ll need to use computed property: return items.sort(function(a, b) { return b[keyname] - a[keyname]; }); When you do a.keyname you’re actually looking for the property keyname in a itself. # [Vue.js] Creating parallax effect with Vuetify using an SVG file vue.jstify provides the v-parallax component to create a typical parallax effect, which creates a 3d effect that makes an image appear to scroll slower than the window: <template> <v-parallax src=”https://cdn.vuetifyjs.com/images/parallax/material.jpg"></v-parallax> </template> Unfortunately it doesn’t work with svg files. Does anybody know whether there is an easy way to create a parallax effect with vuetify or vue, but using an svg file? ### Solution : You can use it if you pass the svg data base64 encoded data:image/svg+xml;base64,[data] where [data] would be the data you get by passing it into an encoder like https://www.base64encode.org/ example: <v-parallax src=”data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/PjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV8xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB2aWV3Qm94PSIwIDAgNTggNTgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDU4IDU4OyIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+PGNpcmNsZSBzdHlsZT0iZmlsbDojRUJCQTE2OyIgY3g9IjI5IiBjeT0iMjkiIHI9IjI5Ii8+PHBvbHlnb24gc3R5bGU9ImZpbGw6I0ZGRkZGRjsiIHBvaW50cz0iNDQsMjkgMjIsNDQgMjIsMjkuMjczIDIyLDE0Ii8+PHBhdGggc3R5bGU9ImZpbGw6I0ZGRkZGRjsiIGQ9Ik0yMiw0NWMtMC4xNiwwLTAuMzIxLTAuMDM4LTAuNDY3LTAuMTE2QzIxLjIwNSw0NC43MTEsMjEsNDQuMzcxLDIxLDQ0VjE0YzAtMC4zNzEsMC4yMDUtMC43MTEsMC41MzMtMC44ODRjMC4zMjgtMC4xNzQsMC43MjQtMC4xNSwxLjAzMSwwLjA1OGwyMiwxNUM0NC44MzYsMjguMzYsNDUsMjguNjY5LDQ1LDI5cy0wLjE2NCwwLjY0LTAuNDM3LDAuODI2bC0yMiwxNUMyMi4zOTQsNDQuOTQxLDIyLjE5Nyw0NSwyMiw0NXogTTIzLDE1Ljg5M3YyNi4yMTVMNDIuMjI1LDI5TDIzLDE1Ljg5M3oiLz48L3N2Zz4=” height=”200”> # [Vue.js] How to dynamically add an Id to the navbar used on laravel/VueJs SPA On my laravel/vuejs Single Page App, when mounting all my components on a single page (welcome.blade.php file), and inside there is included my navbar blade component @include(‘layouts.navbar’). @extends(‘layouts.app’) @section(‘content’) @include(‘layouts.homenavbar’) <router-view></router-view> @endsection My homepage has a transparent background navbar on a huge banner. However, the same navbar is served to the other pages/components but with a coloured background and white colored fonts. I tried using itenary to check if the incoming route is home and add an id that gives the navbar a transparent background, and if the route isn’t home leave the coloured background navbar like so; <nav class=”navbar navbar-default navbar-static-top” id=>”{ Route::currentRouteName() === ‘home’ ? “home_nav” : ‘’}”> -— </nav> and in my css; #home_nav{ background: iceblue; color: #fff; } However, when i go to other routes i keep getting a transparent navbar unless i reload the page. How do i fix this? ### Solution : Try checking window.location.href to get current route on mounted() state of the routes and add the css on that condition ### Solution 2: You could pass a class as a prop with the route: https://router.vuejs.org/guide/essentials/passing-props.html # [Vue.js] VueJS how to write path with parameter correctly I’m following a tutorial and the paths with parameter are not working. data() { return { id: this.$route.params.id,
element: {
title: ‘’,
description: ‘’,
}
}
},
methods: {
getBook() {
const path = ‘http://127.0.0.1:8000/api/v1/books/${this.id}/' axios.get(path).then((response) => { this.element.title = response.data.title this.element.description = response.data.description }) .catch((error) => { console.log(error) }) }, created() { this.getBook() } In console: “GET /api/v1/books/$%7Bthis.id%7D/ HTTP/1.1” 404 2410

What exactly is wrong with what I’m doing?

### Solution :

You need to use backticks :

or just: