link1096 link1097 link1098 link1099 link1100 link1101 link1102 link1103 link1104 link1105 link1106 link1107 link1108 link1109 link1110 link1111 link1112 link1113 link1114 link1115 link1116 link1117 link1118 link1119 link1120 link1121 link1122 link1123 link1124 link1125 link1126 link1127 link1128 link1129 link1130 link1131 link1132 link1133 link1134 link1135 link1136 link1137 link1138 link1139 link1140 link1141 link1142 link1143 link1144 link1145 link1146 link1147 link1148 link1149 link1150 link1151 link1152 link1153 link1154 link1155 link1156 link1157 link1158 link1159 link1160 link1161 link1162 link1163 link1164 link1165 link1166 link1167 link1168 link1169 link1170 link1171 link1172 link1173 link1174 link1175 link1176 link1177 link1178 link1179 link1180 link1181 link1182 link1183 link1184 link1185 link1186 link1187 link1188 link1189 link1190 link1191 link1192 link1193 link1194 link1195 link1196 link1197 link1198 link1199 link1200 link1201 link1202 link1203 link1204 link1205 link1206 link1207 link1208 link1209 link1210 link1211 link1212 link1213 link1214 link1215 link1216 link1217 link1218 link1219 link1220 link1221 link1222 link1223 link1224 link1225 link1226 link1227 link1228 link1229 link1230 link1231 link1232

[Vue.js] Component rendered before correct prop data is passed in from another component

there is a component called EditPost and that uses another component called PostForm. when using vuex store to make an api call to retrieve the post object to be edited from the backend in the EditPost beforeCreate method and using a computed property to get the retrieved post from the store which I then pass as a prop to the PostForm component.
Since the object exists already, its data to be populated in the input fields of the PostForm. But the values of the object aren’t there since the component is rendered before. How can I make sure the data is safely reached before the component gets rendered.

My EditPost component is basically like this:

<template>
<PostForm v-bind:key=”fetchPost” />
</template>

<script>
beforeCreate() {
this.$store.dispatch(‘loadPost’);
}
computed:
fetchPost() {
return this.$store.getters.getPost;
}

</script>

Solution :

You can wait for the loadPost action to be completed in beforeCreated(), then the component won’t be created before the API responds. But be aware that this is not the best practice since the user won’t see anything before the API returns a response.

Example:

<template>
<PostForm v-bind:key=”fetchPost” />
</template>

<script>
async beforeCreate() {
await this.$store.dispatch(‘loadPost’);
}
computed:
fetchPost() {
return this.$store.getters.getPost;
}

</script>

[Vue.js] in vue.js; it's useless to toggle with the attribute 'readonly' of textarea in true or false;

what to do is:

The textarea can be edited when dblclick the textarea;
The textarea can’t be edited when blur;

But now ,it’s useless whatever I toggle with the state of ‘readonly’ attribute;

codesandbox here

Solution :

<input
v-model=”textVal”
:rows=”rows”
:readonly=”status”
:autoHeight=”autoHeight”
class=”textMsg”
@input=”inputing”
@blur=”blur”
\></input>
<button @click=”dblclick”>Test</button>

Hello, I read the example, the code is no problem, the reason for the unexpected effect is the conflict between the ondbclick event and the onblur event. Well, when sorry that I can’t explain this. But my solution is to add a click event to the button to change the value of the text field. Others are unchanged.

Checking the information is the priority of the event. So you can look at this.

[Vue.js] Vue router how can i give query params on root page

export default new Router({
routes: [
{
path: ‘/:userId’,
name: ‘top’,
component: Top
}
]
})

I cannot give a query param like this.

Is it impossible to give param to root view?

export default new Router({
routes: [
{
path: ‘/top/:userId’,
name: ‘top’,
component: Top
}
]
})

I know this is possible , but to give param to root page.

Solution :

You can try :

export default new Router({
routes: [
{
path: ‘/‘,
component: Root,
children: [
{
path: ‘:userId’,
name: ‘top’,
component: Top
}
}
]
})

[Vue.js] Sum different values efficiently

I got an array containing objects like this:

[
{
“id”: 91,
“factor”: 2,
“title”: “Test Product”,
“price”: 50,
“interval”: 1,
“setup”: 0,
“optional”: false
},
{
“id”: 92,
“factor”: 1,
“title”: “Another Test Product”,
“price”: 95,
“interval”: 1,
“setup”: 99,
“optional”: true
},
{
“id”: 93,
“factor”: 1,
“title”: “Just Another Test Product”,
“price”: 12,
“interval”: 1,
“setup”: 0,
“optional”: false
}
]

Alright - now I’d like to create a sum for:

Setup (total)
Price (total)
Price for all products by interval (group by 1,2,3,4, …)

For now when using computed values for each task:

setupTotal: function () {
return this.products.reduce ((acc, product) => acc + (parseFloat (product.setup) * parseFloat (product.factor)), 0);
},

and

monthlyCostsTotal: function () {
let sum = 0;
this.products.forEach (function (product) {
if (product.interval == 1) {
sum += (parseFloat (product.price) * parseFloat (product.factor));
}
});
return sum;
},

and

setupOptional: function () {
let sum = 0;
this.products.forEach (function (product) {
if (product.optional) {
sum += (parseFloat (product.setup) * parseFloat (product.factor));
}
});

return sum;
},

But of course this is not the optimum, because when looping through the array over and over again.

So my question: How can I create a more efficient way to sum values by:

Price total
Price (only optional)
Setup total
Setup (only optional)
Price by interval

Solution :

You could take an object and sum as required.

var data = [{ id: 91, factor: 2, title: “Test Product”, price: 50, interval: 1, setup: 0, optional: false }, { id: 92, factor: 1, title: “Another Test Product”, price: 95, interval: 1, setup: 99, optional: true }, { id: 93, factor: 1, title: “Just Another Test Product”, price: 12, interval: 1, setup: 0, optional: false }],
result = data.reduce((r, { factor, price, interval, setup, optional }) => {
r.price += factor * price;
r.setup += factor * setup;
if (optional) {
r.price_optional += factor * price;
r.setup_optional += factor * setup;
}
r.interval[interval] = (r.interval[interval] || 0) + factor * price;
return r;
}, { price: 0, price_optional: 0, setup: 0, setup_optional: 0, interval: {} });

console.log(result);

Solution 2:

You can use one computed function and return an object containing the results :

calcPrice: function () {
let optional_sum = 0;
let interval_sum = 0;
this.products.forEach (function (product) {

if (product.optional) {
optional_sum += (parseFloat (product.setup) * parseFloat (product.factor));
}

if (product.interval == 1) {
interval_sum += (parseFloat (product.price) * parseFloat (product.factor));
}
});

return {
optional : optional_sum ,
interval : interval_sum
}
};

Then you can use it like: calcPrice.optional OR calcPrice.interval

Hope you get the idea.

[Vue.js] How to access the correct `this` inside a callback?1. Use bind() function2 Store reference to context/this inside another variable3 Arrow function

there is a constructor function which registers an event handler:

function MyConstructor(data, transport) {
this.data = data;
transport.on(‘data’, function () {
alert(this.data);
});
}

// Mock transport object
var transport = {
on: function(event, callback) {
setTimeout(callback, 1000);
}
};

// called as
var obj = new MyConstructor(‘foo’, transport);

However, I’m not able to access the data property of the created object inside the callback. It looks like this does not refer to the object that was created but to an other one.

I also tried to use an object method instead of an anonymous function:

function MyConstructor(data, transport) {
this.data = data;
transport.on(‘data’, this.alert);
}

MyConstructor.prototype.alert = function() {
alert(this.name);
};

but it exhibits the same problems.

How can I access the correct object?

Solution :

What you should know about this

this (aka “the context”) is a special keyword inside each function and its value only depends on how the function was called, not how/when/where it was defined. It is not affected by lexical scopes like other variables (except for arrow functions, see below). Here are some examples:

function foo() {
console.log(this);
}

// normal function call
foo(); // `this` will refer to `window`

// as object method
var obj = {bar: foo};
obj.bar(); // `this` will refer to `obj`

// as constructor function
new foo(); // `this` will refer to an object that inherits from `foo.prototype`

To learn more about this, have a look at the MDN documentation.

How to refer to the correct this

Don’t use this

You actually don’t want to access this in particular, but the object it refers to. That’s why an easy solution is to simply create a new variable that also refers to that object. The variable can have any name, but common ones are self and that.

function MyConstructor(data, transport) {
this.data = data;
var self = this;
transport.on(‘data’, function() {
alert(self.data);
});
}

Since self is a normal variable, it obeys lexical scope rules and is accessible inside the callback. This also has the advantage that you can access the this value of the callback itself.

Explicitly set this of the callback - part 1

It might look like you have no control over the value of this because its value is set automatically, but that is actually not the case.

Every function has the method .bind [docs], which returns a new function with this bound to a value. The function has exactly the same behaviour as the one you called .bind on, only that this was set by you. No matter how or when that function is called, this will always refer to the passed value.

function MyConstructor(data, transport) {
this.data = data;
var boundFunction = (function() { // parenthesis are not necessary
alert(this.data); // but might improve readability
}).bind(this); // <- here we are calling `.bind()`
transport.on(‘data’, boundFunction);
}

In this case, we are binding the callback’s this to the value of MyConstructor’s this.

Note: When binding context for jQuery, use jQuery.proxy [docs] instead. The reason to do this is so that you don’t need to store the reference to the function when unbinding an event callback. jQuery handles that internally.

ECMAScript 6: Use arrow functions

ECMAScript 6 introduces arrow functions, which can be thought of as lambda functions. They don’t have their own this binding. Instead, this is looked up in scope just like a normal variable. That means you don’t have to call .bind. That’s not the only special behaviour they have, please refer to the MDN documentation for more information.

function MyConstructor(data, transport) {
this.data = data;
transport.on(‘data’, () => alert(this.data));
}

Set this of the callback - part 2

Some functions/methods which accept callbacks also accept a value to which the callback’s this should refer to. This is basically the same as binding it yourself, but the function/method does it for you. Array#map [docs] is such a method. Its signature is:

array.map(callback[, thisArg])

The first argument is the callback and the second argument is the value this should refer to. Here is a contrived example:

var arr = [1, 2, 3];
var obj = {multiplier: 42};

var new_arr = arr.map(function(v) {
return v * this.multiplier;
}, obj); // <- here we are passing `obj` as second argument

Note: Whether or not you can pass a value for this is usually mentioned in the documentation of that function/method. For example, jQuery’s $.ajax method [docs] describes an option called context:

This object will be made the context of all Ajax-related callbacks.

Common problem: Using object methods as callbacks/event handlers

Another common manifestation of this problem is when an object method is used as callback/event handler. Functions are first-class citizens in JavaScript and the term “method” is just a colloquial term for a function that is a value of an object property. But that function doesn’t have a specific link to its “containing” object.

Consider the following example:

function Foo() {
this.data = 42,
document.body.onclick = this.method;
}

Foo.prototype.method = function() {
console.log(this.data);
};

The function this.method is assigned as click event handler, but if the document.body is clicked, the value logged will be undefined, because inside the event handler, this refers to the document.body, not the instance of Foo.
As already mentioned at the beginning, what this refers to depends on how the function is called, not how it is defined.
If the code was like the following, it might be more obvious that the function doesn’t have an implicit reference to the object:

function method() {
console.log(this.data);
}

function Foo() {
this.data = 42,
document.body.onclick = this.method;
}

Foo.prototype.method = method;

The solution is the same as mentioned above: If available, use .bind to explicitly bind this to a specific value

document.body.onclick = this.method.bind(this);

or explicitly call the function as a “method” of the object, by using an anonymous function as callback / event handler and assign the object (this) to another variable:

var self = this;
document.body.onclick = function() {
self.method();
};

or use an arrow function:

document.body.onclick = () => this.method();

Solution 2:

Here are several ways to access parent context inside child context -

You can use bind() function.
Store reference to context/this inside another variable(see below example).
Use ES6 Arrow functions.
Alter code/function design/architecture - for this you should have command over design patterns in javascript.

1. Use bind() function

function MyConstructor(data, transport) {
this.data = data;
transport.on(‘data’, ( function () {
alert(this.data);
}).bind(this) );
}
// Mock transport object
var transport = {
on: function(event, callback) {
setTimeout(callback, 1000);
}
};
// called as
var obj = new MyConstructor(‘foo’, transport);

If you are using underscore.js - http://underscorejs.org/#bind

transport.on(‘data’, _.bind(function () {
alert(this.data);
}, this));

2 Store reference to context/this inside another variable

function MyConstructor(data, transport) {
var self = this;
this.data = data;
transport.on(‘data’, function() {
alert(self.data);
});
}

3 Arrow function

function MyConstructor(data, transport) {
this.data = data;
transport.on(‘data’, () => {
alert(this.data);
});
}

Solution 3:

It’s all in the “magic” syntax of calling a method:

object.property();

When you get the property from the object and call it in one go, the object will be the context for the method. If you call the same method, but in separate steps, the context is the global scope (window) instead:

var f = object.property;
f();

When you get the reference of a method, it’s no longer attached to the object, it’s just a reference to a plain function. The same happens when you get the reference to use as a callback:

this.saveNextLevelData(this.setAll);

That’s where you would bind the context to the function:

this.saveNextLevelData(this.setAll.bind(this));

If you are using jQuery you should use the $.proxy method instead, as bind is not supported in all browsers:

this.saveNextLevelData($.proxy(this.setAll, this));

Solution 4:

The trouble with “context”

The term “context” is sometimes used to refer to the object referenced by this. Its use is inappropriate because it doesn’t fit either semantically or technically with ECMAScript’s this.

“Context” means the circumstances surrounding something that adds meaning, or some preceding and following information that gives extra meaning. The term “context” is used in ECMAScript to refer to execution context, which is all the parameters, scope and this within the scope of some executing code.

This is shown in ECMA-262 section 10.4.2:

Set the ThisBinding to the same value as the ThisBinding of the
calling execution context

which clearly indicates that this is part of an execution context.

An execution context provides the surrounding information that adds meaning to code that is being executed. It includes much more information that just the thisBinding.

So the value of this isn’t “context”, it’s just one part of an execution context. It’s essentially a local variable that can be set by the call to any object and in strict mode, to any value at all.

Solution 5:

First, you need to have a clear understanding of scope and behaviour of this keyword in the context of scope.

this & scope :

there are two types of scope in javascript. They are :

1) Global Scope

2) Function Scope

in short, global scope refers to the window object.Variables declared in a global scope are accessible from anywhere.On the other hand function scope resides inside of a function.variable declared inside a function cannot be accessed from outside world normally.this keyword in global scope refers to the window object.this inside function also refers to the window object.So this will always refer to the window until we find a way to manipulate this to indicate a context of our own choosing.

-——————————————————————————-
- -
- Global Scope -
- ( globally “this” refers to window object) -
- -
- function outer_function(callback){ -
- -
- // outer function scope -
- // inside outer function”this” keyword refers to window object - -
- callback() // “this” inside callback also refers window object -

- } -
- -
- function callback_function(){ -
- -
- // function to be passed as callback -
- -
- // here “THIS” refers to window object also -
- -
- } -
- -
- outer_function(callback_function) -
- // invoke with callback -
-——————————————————————————-

Different ways to manipulate this inside callback functions:

Here there is a constructor function called Person. It has a property called name and four method called sayNameVersion1,sayNameVersion2,sayNameVersion3,sayNameVersion4. All four of them has one specific task.Accept a callback and invoke it.The callback has a specific task which is to log the name property of an instance of Person constructor function.

function Person(name){

this.name = name

this.sayNameVersion1 = function(callback){
callback.bind(this)()
}
this.sayNameVersion2 = function(callback){
callback()
}

this.sayNameVersion3 = function(callback){
callback.call(this)
}

this.sayNameVersion4 = function(callback){
callback.apply(this)
}

}

function niceCallback(){

// function to be used as callback

var parentObject = this

console.log(parentObject)

}

Now let’s create an instance from person constructor and invoke different versions of sayNameVersionX ( X refers to 1,2,3,4 ) method with niceCallback to see how many ways we can manipulate the this inside callback to refer to the person instance.

var p1 = new Person(‘zami’) // create an instance of Person constructor

bind :

What bind do is to create a new function with the this keyword set to the provided value.

sayNameVersion1 and sayNameVersion2 use bind to manipulate this of the callback function.

this.sayNameVersion1 = function(callback){
callback.bind(this)()
}
this.sayNameVersion2 = function(callback){
callback()
}

first one bind this with callback inside the method itself.And for the second one callback is passed with the object bound to it.

p1.sayNameVersion1(niceCallback) // pass simply the callback and bind happens inside the sayNameVersion1 method

p1.sayNameVersion2(niceCallback.bind(p1)) // uses bind before passing callback

call :

The first argument of the call method is used as this inside the function that is invoked with call attached to it.

sayNameVersion3 uses call to manipulate the this to refer to the person object that we created, instead of the window object.

this.sayNameVersion3 = function(callback){
callback.call(this)
}

and it is called like the following :

p1.sayNameVersion3(niceCallback)

apply :

Similar to call, first argument of apply refers to the object that will be indicated by this keyword.

sayNameVersion4 uses apply to manipulate this to refer to person object

this.sayNameVersion4 = function(callback){
callback.apply(this)
}

and it is called like the following.Simply the callback is passed,

p1.sayNameVersion4(niceCallback)

Solution 6:

We can not bind this to setTimeout(), as it always execute with global object (Window), if you want to access this context in the callback function then by using bind() to the callback function we can achieve as:

setTimeout(function(){
this.methodName();
}.bind(this), 2000);

Solution 7:

You Should know about “this” Keyword.

As per my view you can implement “this” in three ways
(Self/Arrow function/Bind Method)

A function’s this keyword behaves a little differently in JavaScript compared to other languages.

It also has some differences between strict mode and non-strict mode.

In most cases, the value of this is determined by how a function is called.

It can’t be set by assignment during execution, and it may be different each time the function is called.

ES5 introduced the bind() method to set the value of a function’s this regardless of how it’s called,

and ES2015 introduced arrow functions which don’t provide their own this binding (it retains the this value of the enclosing lexical context).

Method1: Self - Self is being used to maintain a reference to the original this even as the context is changing. It’s a technique often used in event handlers (especially in closures).

Reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

function MyConstructor(data, transport) {
this.data = data;
var self = this;
transport.on(‘data’, function () {
alert(self.data);
});
}

Method2: Arrow function - An arrow function expression is a syntactically compact alternative to a regular function expression,

although without its own bindings to the this, arguments, super, or new.target keywords.

Arrow function expressions are ill suited as methods, and they cannot be used as constructors.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow\_functions

function MyConstructor(data, transport) {
this.data = data;
transport.on(‘data’,()=> {
alert(this.data);
});
}

Method3:Bind- The bind() method creates a new function that,

when called, has its this keyword set to the provided value,

with a given sequence of arguments preceding any provided when the new function is called.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_objects/Function/bind

function MyConstructor(data, transport) {
this.data = data;
transport.on(‘data’,(function() {
alert(this.data);
}).bind(this);

Solution 8:

Currently there is another approach possible if classes are used in code.

With support of class fields it’s possible to make it next way:

class someView {
onSomeInputKeyUp = (event) => {
console.log(this); // this refers to correct value
// ….
someInitMethod() {
//…
someInput.addEventListener(‘input’, this.onSomeInputKeyUp)

For sure under the hood it’s all old good arrow function that bind context but in this form it looks much more clear that explicit binding.

Since it’s Stage 3 Proposal you will need babel and appropriate babel plugin to process it as for now(08/2018).

Solution 9:

Another approach, which is the standard way since DOM2 to bind this within the event listener, that let you always remove the listener (among other benefits), is the handleEvent(evt)method from the EventListener interface:

var obj = {
handleEvent(e) {
// always true
console.log(this === obj);
}
};

document.body.addEventListener(‘click’, obj);

Detailed information about using handleEvent can be found here: https://medium.com/@WebReflection/dom-handleevent-a-cross-platform-standard-since-year-2000-5bf17287fd38

Solution 10:

The question revolves around how this keyword behaves in javascript. this behaves differently as below,

The value of this is usually determined by a functions execution context.
In the global scope, this refers to the global object (the window object).
If strict mode is enabled for any function then the value of this will be undefined as in strict mode, global object refers to undefined in place of the window object.
The object that is standing before the dot is what the this keyword will be bound to.
We can set the value of this explicitly with call(), bind(), and apply()
When the new keyword is used (a constructor), this is bound to the new object being created.
Arrow Functions dont bind thisinstead, this is bound lexically (i.e. based on the original context)

As most of the answers suggest, we can use Arrow function or bind() Method or Self var. I would quote a point about lambdas (Arrow function) from Google JavaScript Style Guide

Prefer using arrow functions over f.bind(this), and especially over
goog.bind(f, this). Avoid writing const self = this. Arrow functions
are particularly useful for callbacks, which sometimes pass unexpected
additional arguments.

Google clearly recommends to use lambdas rather than bind or const self = this

So the best solution would be to use lambdas as below,

function MyConstructor(data, transport) {
this.data = data;
transport.on(‘data’, () => {
alert(this.data);
});
}

References:

https://medium.com/tech-tajawal/javascript-this-4-rules-7354abdb274c
arrow-functions-vs-bind

[Vue.js] how to fix Unknown custom element <router-view>

I import the vue-route to my app.js in my laravel vue.js website. Sadly, there’s an error. Can you please guide me thanks

app.js

require(‘./bootstrap’);

window.vue.js = require(‘vue’);
import VueRouter from ‘vue-router’
Vue.use(VueRouter)

let routes = [
{path: ‘/‘, component: require(‘./components/Welcome.vue’) }

]

const router = new VueRouter({
mode: ‘history’,
routes
})

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

master.blade.php

<!– Scripts –>
<script src=”{ asset(‘js/app.js’) }” defer></script>

<!– Styles –>
<link href=”{ asset(‘css/app.css’) }” rel=”stylesheet”>
<body>
<div id=”app”>

@yield(‘content’)

</div>
</body

welcome.blade.php

@extends(‘layouts.master’)

@section(‘content’)

<router-view></router-view>
<vue-progress-bar> </vue-progress-bar>
@endsection

The result should be the Welcome.vue.js will display.

Solution :

If you use a newer version of Vue.js you should have .default to require(‘./components/Welcome.vue’)

So line 5 would look like this

{path: ‘/‘, component: require(‘./components/Welcome.vue’).default }

Stack Overflow: Why need default after require() method in Vue?

Solution 2:

As per documentation, you should inject router option to make the whole app router aware.

So you should have something like this:

const app = new Vue({
router
}).$mount(‘#app’)

I think this is duplicate of this.

[Vue.js] Side bar image disappearing when page reload Laravel

I’m using vue-router to navigate between the menus and doing some request with axios. Whenever the page reloads, the image on the side bar dissapears. I’m not sure what’s causing this. Thanks in advance.

BEFORE

AFTER reload

<aside class=”main-sidebar elevation-4” style=”background-color:#F4F6F9”>
<a href=”#” class=”brand-link”>
<img src=”./img/logo.png” class=”brand-image img-thumbnail elevation-3”>
<img src=”./img/uthm.png” class=”brand-image img-thumbnail elevation-3”>
<br>
</a>
</aside>

Solution :

the reload may possibly take you a level deeper into the site and the links to you images are now becoming invalid.

eg.

http://www.example.com/page1

# Works fine so far
../path/to/image.jpg

on reload:

http://www.example.com/page1/page2

# the image link now needs to revert back one level
../../path/to/image.jpg

I had a similar issue, where my index page worked fine but as soon as I went a directory in it freaked out, I realised I needed a better way to assign img src’s

Update
My fix was to use an inbuilt command in laravel that gave the root path to the file. You might have to find if vue.js has a similar function to direct always to the root folder no matter where you are.

A quick fix is to give the full directory path

# instead of the relative path
../path/to/image.com

# Try
http://example.com/root/path/to/image.jpg

# or if offline

http://127.0.0.1/root/path/to/image.jpg

Solution 2:

Can you please give us more details .
I will participate in this with my sugestion , if you are using vue-router and when you reload the page ,did the link change , i know for sure that is the problem
As an example , when the reload this url (https://127.0.0.1/test/) , it will be (https://127.0.0.1/test/#/) the path that you are loading the pictures from will change , so you need to configure the app.js in this path (resources\assets\js) , and you need to add this line to the route .

const router = new VueRouter({
mode:’history’,
routes

})

if you do so , the url will be the some after you reload the page.

[Vue.js] TypeError (0 , _ignore.getFileExtensions) is not a function

vue.js CLI v3.5.5

I installed vue-cli and created a new project through the create command, but at the end there is an error. What should I do?

? Please pick a preset: Manually select features

? Check the features needed for the project: Babel, Router, Linter

? Use history mode for router? (Requires proper server setup for index fallback in production) Yes

? Pick a linter / formatter config: Airbnb

? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection)Lint on save

? Where do you prefer placing config for Babel, PostCSS, ESLint, etc.? In package.json

? Save this as a preset for future projects? No

? Pick the package manager to use when installing dependencies: Yarn

ERROR TypeError: (0 , _ignore.getFileExtensions) is not a function
Occurred while linting /Users/untca/Sites/vue-flickr/src/main.js:2
TypeError: (0 , _ignore.getFileExtensions) is not a function
Occurred while linting /Users/untca/Sites/vue-flickr/src/main.js:2

at checkSourceValue (/Users/untca/Sites/vue-flickr/node_modules/eslint-plugin-import/lib/rules/no-useless-path-segments.js:103:60)
at checkSourceValue (/Users/untca/Sites/vue-flickr/node_modules/eslint-module-utils/moduleVisitor.js:29:5)
at checkSource (/Users/untca/Sites/vue-flickr/node_modules/eslint-module-utils/moduleVisitor.js:34:5)
at listeners.(anonymous function).forEach.listener (/Users/untca/Sites/vue-flickr/node_modules/eslint/lib/util/safe-emitter.js:45:58)
at Array.forEach (<anonymous>)
at Object.emit (/Users/untca/Sites/vue-flickr/node_modules/eslint/lib/util/safe-emitter.js:45:38)
at NodeEventGenerator.applySelector (/Users/untca/Sites/vue-flickr/node_modules/eslint/lib/util/node-event-generator.js:251:26)
at NodeEventGenerator.applySelectors (/Users/untca/Sites/vue-flickr/node_modules/eslint/lib/util/node-event-generator.js:280:22)
at NodeEventGenerator.enterNode (/Users/untca/Sites/vue-flickr/node_modules/eslint/lib/util/node-event-generator.js:294:14)
at CodePathAnalyzer.enterNode (/Users/untca/Sites/vue-flickr/node_modules/eslint/lib/code-path-analysis/code-path-analyzer.js:632:23)

Solution :

Thiis a known issue with an upstream ESLint plugin when using the airbnb rules (eslint-plugin-import#1322). The workaround is to add an ESLint rule that disables usage of the plugin:

// .eslintrc.js
module.exports = {
rules: {
“import/no-useless-path-segments”: “off”, // add this rule
},
};

[Vue.js] Setting nested object property by string path

there is 3 select boxes, and I would like them to reset a certain field on select. How can I make it dynamic, so that it is reusable?

Here’s an excerpt of my code:

v-on:select=”getDate(‘{ route(‘api.v1.get.date’) }’, ‘input1’, [‘form.company.input2’, ‘form.company.input3’], $event)”

getDate(url, obj, obj2, event){

let current = this

current[obj] = ‘’
current[obj2[0]] = ‘’
current[obj2[1]] = ‘’

}

When obj is at the root level of the vue.js instance (i.e., current[obj]), it sets the property correctly; but not when obj is a nested object.

Solution :

In JavaScript, property accessors do not allow nested object paths, which is what you have in the dot-separated string. By using that string, you’re actually creating a property on the root vue.js instance instead of setting a nested property, similar to this:

this[‘form.company.input2’] = ‘’ // XXX: creates `form.company.input2` prop
this.form.company.input2 = ‘’ // sets `input2`

To set the object value by path, you could create a method that uses the object path to navigate the current vue.js instance’s data properties via this:

methods: {
getDate(url, obj, obj2, event) {
this.setValue(obj, ‘’)
this.setValue(obj2[0], ‘’)
this.setValue(obj2[1], ‘’)
},
setValue(path, value) {
let obj = this
const parts = path.split(‘.’)
while (parts.length > 1 && obj.hasOwnProperty(parts[0])) {
obj = obj[parts.shift()]
}
obj[parts[0]] = value
}
}

new Vue({
el: ‘#app’,
data() {
return {
input1: ‘input1’,
form: {
company: {
input2: ‘input2’,
input3: ‘input3’
}
}
}
},
methods: {
getDate(url, obj, obj2, event) {
this.setValue(obj, ‘’)
this.setValue(obj2[0], ‘’)
this.setValue(obj2[1], ‘’)
},
setValue(path, value) {
let obj = this
const parts = path.split(‘.’)
while (parts.length > 1 && obj.hasOwnProperty(parts[0])) {
obj = obj[parts.shift()]
}
obj[parts[0]] = value
},
route(prop) {
return prop
}
}
})
<script src=”https://unpkg.com/vue@2.6.10"></script>

<div id=”app”>
<input v-model=”input1”>
<input v-model=”form.company.input2”>
<input v-model=”form.company.input3”>

<button @click=”getDate(route(‘api.v1.get.date’), ‘input1’, [‘form.company.input2’, ‘form.company.input3’], $event)”>
Reset data
</button>
</div>

Alternatively, you could use a library (such as lodash’s _.set):

methods: {
getDate(url, obj, obj2, event) {
_.set(this, obj, ‘’)
_.set(this, obj2[0], ‘’)
_.set(this, obj2[1], ‘’)
}
}

new Vue({
el: ‘#app’,
data() {
return {
input1: ‘input1’,
form: {
company: {
input2: ‘input2’,
input3: ‘input3’
}
}
}
},
methods: {
getDate(url, obj, obj2, event) {
_.set(this, obj, ‘’)
_.set(this, obj2[0], ‘’)
_.set(this, obj2[1], ‘’)
},
route(prop) {
return prop
}
}
})
<script src=”https://unpkg.com/lodash@4.17.11/lodash.js"></script>
<script src=”https://unpkg.com/vue@2.6.10"></script>

<div id=”app”>
<input v-model=”input1”>
<input v-model=”form.company.input2”>
<input v-model=”form.company.input3”>

<button @click=”getDate(route(‘api.v1.get.date’), ‘input1’, [‘form.company.input2’, ‘form.company.input3’], $event)”>
Reset data
</button>
</div>

Solution 2:

Try to use this.$set function as follows:

this.$set(current,obj,’’);
this.$set(current,obj2[0],’’);
this.$set(current,obj2[1],’’);

learn more about that function here

[Vue.js] How to Filter Data Array by Week Filter()

Currently trying to filter my data array by week, there is been able to filter by day quite easily however am struggling with dates between x and y (eg by week).

there is tried setting a start date and end date (today) and then trying to return the dates less than or equal to the start and end dates but am failing.

Data array date format: dd/mm/yyyy (01/01/2000)

The user will select which filter to use (hence switch() ) case 7 being filter by 7 days.

computed: {
appointments: function () {

var today = new Date();
var dd = String(today.getDate()).padStart(2, ‘0’);
var mm = String(today.getMonth() + 1).padStart(2, ‘0’); //January is 0!
var yyyy = today.getFullYear();

var data = this.$store.state.appointments;

this.filter1_color = “grey”;
this.filter2_color = “grey”;

switch (this.dateFilter) {
case 0:
break;

case 1:
console.log(“case1: “ + today)
return data.filter(word => word.date == today);

case 7:

/// WORKING /// (ex. edit)
var week = [];

var today = moment();
var sevenDaysBefore = today.subtract(7, ‘days’);

for (var i = 0; i < data.length; i++) {
let momentDate = moment(data[i].date, ‘DD/MM/YYYY’)
let newDate = momentDate.format(“DD/MM/YYYY”)
if (momentDate.isBetween(sevenDaysBefore, moment(), null, ‘[]‘)) week.push(data[i]);
}

return week
///

}

return data;
},

I need to filter the data to only show items in the array with dates equal to the dates in the last 7 days.

Solution :

You can use method isBetween of moment js library with current date. You can subtract 7 days to current date with subtract(7, ‘days’).

You can check more about isBetween method in moment js library documentation. The third parameter of the method is the granularity, and it seems that in the case it should ‘days’

const today = moment();
const sevenDaysBefore = moment().subtract(7, ‘days’);

console.log(‘Today is ‘ + today.format(‘MMM Do YYYY’));
console.log(‘Is ‘ + today.format(‘MMM Do YYYY’) + ‘ included in the last seven days?’);
console.log(today.isBetween(sevenDaysBefore, today, ‘day’, ‘[]‘));

console.log(‘Is ‘ + sevenDaysBefore.format(‘MMM Do YYYY’) + ‘ included in the last seven days?’);
console.log(sevenDaysBefore.isBetween(sevenDaysBefore, today, ‘day’, ‘[]‘));

const eightDaysBefore = moment().subtract(8, ‘days’);
console.log(‘Is ‘ + eightDaysBefore.format(‘MMM Do YYYY’) + ‘ included in the last seven days?’);
console.log(eightDaysBefore.isBetween(sevenDaysBefore, today, ‘day’, ‘[]‘));

const oneDayAfter = moment().add(1, ‘days’);
console.log(‘Is ‘ + oneDayAfter.format(‘MMM Do YYYY’) + ‘ included in the last seven days?’);
console.log(oneDayAfter.isBetween(sevenDaysBefore, today, ‘day’, ‘[]‘));
<script src=”https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>

Solution 2:

If you don’t want to or cannot use a library like moment.js, and also don’t mind an ad-hoc implementation with certain restrictions:

Note

I recommend to use a library for working with Date objects, especially when it comes to parsing a string to a date. Too many things can go wrong when doing it by hand. If possible, use the answer of @f-CJ

These parts allow you to create a Date object from a string. However, the resulting Date is always converted to local time and the string needs to have a certain formatting (the one you showed in the question). If you need support for UTC, this won’t work. Also, it cannot be used to parse a date string with ISO formatting.

const OFFSET_TO_UTC = new Date().getTimezoneOffset();

function parseDateString (dateString, sep) {
var parts = dateString.split(sep);
return parts.map(n => Number(n));
}

function localizeDate (pattern, parts) {
return pattern.reduce((acc, pat, i) => {
switch (pat) {
case ‘d’:
return Object.assign(acc, { day: parts[i] });
case ‘m’:
return Object.assign(acc, { month: parts[i] });
case ‘y’:
return Object.assign(acc, { year: parts[i] });
default:
return acc;
}
}, {});
}

function toDate (localized) {
return new Date(
localized.year,
localized.month - 1,
localized.day,
0, 0 - OFFSET_TO_UTC, 0);
}

function parseDate (pattern, sep, dateString) {
return toDate(localizeDate(pattern, parseDateString(dateString, sep)));
}

// try it:

const dStringUS = ‘04/04/2019’; // mm/dd/yyyy
const dStringDE = ‘04.04.2019’; // dd/mm/yyyy

const dateUS = parseDate([‘m’, ‘d’, ‘y’], ‘/‘, dStringUS);
const dateDE = parseDate([‘d’, ‘m’, ‘y’], ‘.’, dStringDE);

console.log(dateUS);
console.log(dateDE);

Based on it, you can write yourself a generic filtering function:

const OFFSET_TO_UTC = new Date().getTimezoneOffset();

function parseDateString (dateString, sep) {
var parts = dateString.split(sep);
return parts.map(n => Number(n));
}

function localizeDate (pattern, parts) {
return pattern.reduce((acc, pat, i) => {
switch (pat) {
case ‘d’:
return Object.assign(acc, { day: parts[i] });
case ‘m’:
return Object.assign(acc, { month: parts[i] });
case ‘y’:
return Object.assign(acc, { year: parts[i] });
default:
return acc;
}
}, {});
}

function toDate (localized) {
return new Date(
localized.year,
localized.month - 1,
localized.day,
0, 0 - OFFSET_TO_UTC, 0);
}

function parseDate (pattern, sep, dateString) {
return toDate(localizeDate(pattern, parseDateString(dateString, sep)));
}

const data = [{
value: 0,
date: ‘04/05/2019’
}, {
value: 1,
date: ‘04/07/2019’
}, {
value: 2,
date: ‘03/07/2019’
}];

function filterByDatePattern (pattern, sep) {
return function (date, list) {
return list.filter(item => {
var itemDate = parseDate(pattern, sep, item.date);
return itemDate >= date;
});
}
}

const onlyUSUntil = filterByDatePattern([‘m’, ‘d’, ‘y’], ‘/‘);
console.log(onlyUSUntil(new Date(2019, 3, 1), data));