link3014 link3015 link3016 link3017 link3018 link3019 link3020 link3021 link3022 link3023 link3024 link3025 link3026 link3027 link3028 link3029 link3030 link3031 link3032 link3033 link3034 link3035 link3036 link3037 link3038 link3039 link3040 link3041 link3042 link3043 link3044 link3045 link3046 link3047 link3048 link3049 link3050 link3051 link3052 link3053 link3054 link3055 link3056 link3057 link3058 link3059 link3060 link3061 link3062 link3063 link3064 link3065 link3066 link3067 link3068 link3069 link3070 link3071 link3072 link3073 link3074 link3075 link3076 link3077 link3078 link3079 link3080 link3081 link3082 link3083 link3084 link3085 link3086 link3087 link3088 link3089 link3090 link3091 link3092 link3093 link3094 link3095 link3096 link3097 link3098 link3099 link3100 link3101 link3102 link3103 link3104 link3105 link3106 link3107 link3108 link3109 link3110 link3111 link3112 link3113 link3114 link3115 link3116 link3117 link3118 link3119 link3120 link3121 link3122 link3123 link3124 link3125 link3126 link3127 link3128 link3129 link3130 link3131 link3132 link3133 link3134 link3135 link3136 link3137 link3138 link3139 link3140 link3141 link3142 link3143 link3144 link3145 link3146 link3147 link3148 link3149 link3150

[Vue.js] How to change vuetify calendar interval format to 24 hours? Subscribe to RSS

I’m using vuetify calendar with type week and it shows time in 12 hour format with AM and PM. How do i change that to 24 hour format?

I looked at the documentation and didn’t find much, except that u can pass interval-format prop that expects a function. Also found a function at vuetify github.

<v-calendar
:now=”today”
:value=”today”
color=”primary”
locale=”et”
type=”week”
:interval-format=”intervalFormat”
\>
</v-calendar>

methods: {
intervalFormat() {
const longOptions = { timeZone: ‘UTC’, hour12: true, hour: ‘2-digit’, minute: ‘2-digit’ }
const shortOptions = { timeZone: ‘UTC’, hour12: true, hour: ‘numeric’, minute: ‘2-digit’ }
const shortHourOptions = { timeZone: ‘UTC’, hour12: true, hour: ‘numeric’ }

return longOptions
}
}

I wanted 24 hour format but it’s still 12 hour format

Solution :

Got it.

intervalFormat(interval) {
return interval.time
}

[Vue.js] Vue JS ternary expression Subscribe to RSS

i’m using vue.js JS and am trying to use a ternary expression to conditionally change the value of something, I’m struggling with how to convert the following to a ternary expression, here’s my method, by default: isLoading is true

fetchData(showLoading) {
if (showLoading) {
this.isLoading = true
} else {
this.isLoading = false
}
}

Solution :

Don’t use the conditional operator here, just assign showLoading to isLoading, assuming you’re passing a boolean:

this.isLoading = showLoading;

If you’re not necessarily passing a boolean, then cast to boolean first (if needed):

this.isLoading = Boolean(showLoading);

If you had to use the conditional operator, it would be:

this.isLoading = showLoading ? true : false;

[Vue.js] Vue - Populate table with Axios Subscribe to RSS

Im trying to populate table with axios and vue, like this:

<div class=”container h-100”>
<div class=”row h-100 justify-content-center align-items-center”>
<table class=”table table-striped table-bordered table-hover”>
<thead class=”thead-dark”>
<tr>
<th>#</th>
<th>First</th>
<th>Last</th>
<th>Handle</th>
</tr>
</thead>
<tbody>
<tr v-for=”user in users”>
<td>{user.name}</td>
<td>{user.username}</td>
<td>{user.email}</td>
<td>{user.phone}</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
<script src=”https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
<script src=”https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
var users;
axios.get(‘https://jsonplaceholder.typicode.com/users')
.then(function (response) {
users = response[‘data’];
})
.catch(function (error) {
console.log(error);
})
</script>

The problem is that {user.name} returns ‘{user.name}’ , doesnt show real data. Anybody know how can I use vue.js to show array data in a table?

UPDATE

I updated with this code but view still empty. If i return this.users in the script return a object with values.

<!DOCTYPE html>
<html lang=”en”>

<head>
<meta charset=”UTF-8”>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0”>
<meta http-equiv=”X-UA-Compatible” content=”ie=edge”>
<link rel=”stylesheet” href=”https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<title>Tabla</title>
<style>
body,
html {
height: 100%;
}
</style>
</head>

<body>
<div id=”tabla”>
<div class=”container h-100”>
<div class=”row h-100 justify-content-center align-items-center”>
<table class=”table table-striped table-bordered table-hover text-center”>
<thead class=”thead-dark”>
<tr>
<th>Name</th>
<th>Username</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr v-for=”user in users”>
<td>{user.name}</td>
<td>{user.username}</td>
<td>{user.email}</td>
<td>{user.phone}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
<script src=”https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
<script src=”https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
new Vue({
el: ‘#tabla’,
data: {
users: [],
},
created: function () {
this.load();
},
methods: {
load: function () {
axios
.get(‘https://jsonplaceholder.typicode.com/users')
.then(function (response) {
this.users = response.data;
})
.catch(function (error) {
console.log(error);
})
}
}
})
</script>

</html>

Solution :

Update

Issue is with this inside the axios api callback.

This is not the right place to explain this very explanatory.

In simple context - this is the object that the function is the property of.
And In the case this get window object as you are using function which is not lexically scoped. To make it lexically scoped Use ES6 Arrow fn

new Vue({
el: “#app”,
data() {
return {
users: []
}
},
mounted: function() {
axios
.get(‘https://jsonplaceholder.typicode.com/users')
.then(response => {
this.users = response.data
})
.catch(function (error) {
console.log(error);
})
}
})
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<script src=”https://unpkg.com/axios/dist/axios.min.js"></script>

<div id=”app”>

<table>
<thead class=”thead-dark”>
<tr>
<th>#</th>
<th>First</th>
<th>Last</th>
<th>Handle</th>
</tr>
</thead>
<tbody>
<tr v-for=”user in users” :key=”user.email”>
<td>{user.name}</td>
<td>{user.username}</td>
<td>{user.email}</td>
<td>{user.phone}</td>
</tr>
</tbody>
</table>
</div>

You need to create vue.js instance which binds the html to it.

Let say you have html which has a id = app

<div id=”app”>
{ message }
</div>

Now if you want this piece of html to use vue, you need to bind it.

var app = new Vue({
el: ‘#app’, // This property el binds the container #app
data: {
message: ‘Hello Vue!’ // here you create the data values you want to use
}
})

However I would suggest you to look through vue.js awesome documentation before using it - vue.js JS

Solution 2:

You don’t define users in a vue.js instance. You should create a vue.js instance and define users in the data part.

<body>
<div id=”app”>
// Paste all of the html in here
</div>
</body>
<script src=”https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
<script src=”https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
new Vue({
el: ‘#app’,
data: {
users: []
},
mounted: function() {
axios
.get(‘https://jsonplaceholder.typicode.com/users')
.then(function (response) {
this.users = response[‘data’];
})
.catch(function (error) {
console.log(error);
})
}
})
</script>

Solution 3:

Have you properly initiated vue.js ?

Take a look at this official documentation.
https://vuejs.org/v2/guide/index.html

If you have initiated the vue.js in other file and this is only component definition,
you should still need to follow the component definition.
And call the Axios inside mount lifecycle and define users as data or computed.

[Vue.js] Vue.js using local javascript file functions in component Uncaught TypeError __WEBPACK_IMPORTED_MODULE_0__.writeSomething is not a function Subscribe to RSS

when trying to import a local JS file into a single file component in a vue.js application. My application is a scaffold generated by vue-CLI (ver 3.8.2).

Here are my relevant code snippets (all other code in application is unchanged from generated code):

/path/to/app-vue/src/components/HelloWorld.vue

<template>
<div class=”hello”>
<Module1/>
</div>
</template>

<script lang=”ts”>
import { Component, Prop, vue.js } from ‘vue-property-decorator’;
import Module1 from ‘./Module1.vue’;

@Component({
components: {
Module1,
}
})
export default class HelloWorld extends vue.js {
@Prop() private msg!: string;
}

</script>

<!– Add “scoped” attribute to limit CSS to this component only –>
<style scoped>
</style>

/path/to/vue-app/src/components/Module1.vue

<template>
<div class=”module1”>
Module2
</div>
</template>

<script>
import { Component, Prop, vue.js } from ‘vue-property-decorator’;
import Module2 from ‘./Module2.vue’;

@Component({
components: {
Module2,
},
})
export default class Module1 extends vue.js {
}
</script>

/path/to/vue-app/Module2.vue

<template>
<div id=’demo’>
</div>
</template>

<script>
import foo from ‘../assets/js/foo’;

foo.writeSomething(‘#demo’);
</script>

/path/to/vue-app/src/assets/js/foo.js

function writeSomething(el) {
elem = window.document.getElementById(el);
elem.innerHTML = ‘Hello World!’;
}

export default {
writeSomething
}

When I run npm run serve and navigate to ‘/‘ in the browser, I get the following error messages in the console:

“export ‘default’ (imported as ‘mod’) was not found in
‘-!../../node_modules/cache-loader/dist/cjs.js??ref–12-0!../../node_modules/babel-loader/lib/index.js!../../node_modules/cache-loader/dist/cjs.js??ref–0-0!../../node_modules/vue-loader/lib/index.js??vue-loader-options!./Module2.vue?vue&type=script&lang=js&’

And in the browser DevTools console, I get the following stack trace:

Uncaught TypeError: _assets_js_foo__WEBPACK_IMPORTED_MODULE_0__.writeSomething is not a function
at eval (Module2.vue?df9f:9)
at Module../node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/Module2.vue?vue&type=script&lang=js& (app.js:1078)
at __webpack_require__ (app.js:767)
at fn (app.js:130)
at eval (Module2.vue?35cf:1)
at Module../src/components/Module2.vue?vue&type=script&lang=js& (app.js:3448)
at __webpack_require__ (app.js:767)
at fn (app.js:130)
at eval (Module2.vue?6104:1)
at Module../src/components/Module2.vue.js (app.js:3436)

How do I load local javascript files into a Single File Component, and use functions defined in the loaded Javascript (within the component)?

Solution :

You need to explicitely export the function and import it using its name.

Module2.vue

import { writeSomething } from ‘../assets/js/foo.js’;
writeSomething(‘#demo’);

export default { …

foo.js

export function writeSomething(el) {
elem = window.document.getElementById(el);
elem.innerHTML = ‘Hello World!’;
}

If you are using typescript, make sure that you can import js modules

you can also export a default module

function writeSomething(el) {
elem = window.document.getElementById(el);
elem.innerHTML = ‘Hello World!’;
}

export default {
writeSomething
}

and import it as

import foo from ‘../assets/foo.js’;

// …
foo.writeSomething(‘#demo’);

[Vue.js] $ref typecast causes compiler to require semicolon to terminate line Subscribe to RSS

there is a vue.js component which makes use of vue-boostrap Modal component, with a definition that looks something like this:

<template>
<div>
<b-modal ref=”NewProjectDialog” id=”NewProjectDialog” centered>
</b-modal>
</div>
</template>

<script lang=”ts”>
import { Component, Vue, Prop } from ‘vue-property-decorator’
import {BModal} from ‘bootstrap-vue’

@Component()
export default class Projects extends vue.js {
save_project() {
(this.$refs[‘NewProjectDialog’] as BModal).hide()
}
}

The above code works correctly, however there appears to be a mistake in the way there is cast $ref[‘NewProjectDialog’], because it appears that the compiler picks up the preceding line as part of the expression, e.g. the following code generates a “Cannot invoke an expression whose type lacks a call signature.” error:

save_project() {
console.log(‘any code line without a semicolon fails’)
(this.$refs[‘NewProjectDialog’] as BModal).hide()
}

but the following code compiles fine:

save_project() {
console.log(‘any code line without a semicolon fails’);
(this.$refs[‘NewProjectDialog’] as BModal).hide()
}

Can anyone explain why I need the line separator for the code to work correctly?

Solution :

The semicolon is needed here to remove ambiguity in the syntax.

The problem is not specifically that you are doing a cast, but that the cast needs to be wrapped in brackets.

It’s probably easier to understand if we strip away the other parts of the code and just look at the syntax:

foo()
(bar).fizz()
// vs
foo();
(bar).fixx

Looks the same, but to the interpreter, the first one looks like

foo()(bar).fizz()

i.e you’re calling the result of foo() as a function.

If we define our variables differently this syntax make a lot of sense:

function foo() {
return a => a*2;
}
var bar = 2;

foo()
(bar).toFixed(2);
// Prints 4.00

Adding the semicolon tells the interpreter that foo() is a seperate call and the next line is not operating on its result as a function.

Solution 2:

Bootstrapvue.js v2.0.0-rc.21 (and newer) has a simpler method for showing and hiding modals:

this.$bvModal.hide(‘id-of-modal’)
this.$bvModal.show(‘id-of-modal’)

The above this.$bvModal has type declarations, so it should work without any casting.

[Vue.js] Vue.js not working on fresh Laravel 5.8 project Subscribe to RSS

I’ve created a new Laravel project with laravel new test. Then I’ve ran npm install and npm run dev. I changed the welcome.blade.php file to

<!DOCTYPE html>
<html>
<head>
<script type=”text/javascript” href=”{ mix(‘js/app.js’) }”></script>
</head>
<body>
<div id=”app”>
<example-component></example-component>
</div>
</body>
</html>

and that’s the only change I’ve made. However the page is blank, and the vue.js devtools extensions on Chrome says “Vue.js not detected”.

Since Laravel provides nearly out-of-the-box support for Vue, I can’t see what’s going wrong. The relevant files are below (untouched from Laravel’s installation).

/resources/js/app.js (which compiles successfully with npm run dev to /public/js/app.js)

/**
* First we will load all of this project’s JavaScript dependencies which
* includes vue.js and other libraries. It is a great starting point when
* building robust, powerful web applications using vue.js and Laravel.
*/

require(‘./bootstrap’);

window.vue.js = require(‘vue’);

/**
* The following block of code may be used to automatically register your
* vue.js components. It will recursively scan this directory for the Vue
* components and automatically register them with their “basename”.
*
* Eg. ./components/ExampleComponent.vue.js -> <example-component></example-component>
*/

// const files = require.context(‘./‘, true, /\.vue$/i);
// files.keys().map(key => Vue.component(key.split(‘/‘).pop().split(‘.’)[0], files(key).default));

Vue.component(‘example-component’, require(‘./components/ExampleComponent.vue’));

/**
* Next, we will create a fresh vue.js application instance and attach it to
* the page. Then, you may begin adding components to this application
* or customize the JavaScript scaffolding to fit the unique needs.
*/

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

/resources/js/components/ExampleComponent.vue:

<template>
<div class=”container”>
<div class=”row justify-content-center”>
<div class=”col-md-8”>
<div class=”card”>
<div class=”card-header”>Example Component</div>

<div class=”card-body”>
I’m an example component.
</div>
</div>
</div>
</div>
</div>
</template>

<script>
export default {
mounted() {
console.log(‘Component mounted.’)
}
}
</script>

webpack.mix.js:

const mix = require(‘laravel-mix’);

/*
|————————————————————————–
| Mix Asset Management
|————————————————————————–
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for the Laravel application. By default, we are compiling the Sass
| file for the application as well as bundling up all the JS files.
|
*/

mix.js(‘resources/js/app.js’, ‘public/js’)
.sass(‘resources/sass/app.scss’, ‘public/css’);

package.json:

{
“private”: true,
“scripts”: {
“dev”: “npm run development”,
“development”: “cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js –progress –hide-modules –config=node_modules/laravel-mix/setup/webpack.config.js”,
“watch”: “npm run development — –watch”,
“watch-poll”: “npm run watch — –watch-poll”,
“hot”: “cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js –inline –hot –config=node_modules/laravel-mix/setup/webpack.config.js”,
“prod”: “npm run production”,
“production”: “cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js –no-progress –hide-modules –config=node_modules/laravel-mix/setup/webpack.config.js”
},
“devDependencies”: {
“axios”: “^0.19”,
“bootstrap”: “^4.1.0”,
“cross-env”: “^5.1”,
“jquery”: “^3.2”,
“laravel-mix”: “^4.0.7”,
“lodash”: “^4.17.5”,
“popper.js”: “^1.12”,
“resolve-url-loader”: “^2.3.1”,
“sass”: “^1.15.2”,
“sass-loader”: “^7.1.0”,
“vue”: “^2.5.17”,
“vue-template-compiler”: “^2.6.10”
}
}

Again, these are all simply as they get installed.

Any ideas? The blank page is successfully loading the compiled app.js file, which looks as it should (e.g. there’s mentions of vue.js and example-component).

Solution :

You need to defer the script

<script href=”{ asset(‘js/app.js’) defer}”></script>

The reason is by doing this:

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

Javascript will be loaded as soon as it can and the element #app may not have been loaded yet. By defering, the JS will be executed once the document is loaded.

Alternatively, you can use jQuery to wait for the document to be loaded with $(document).ready (but don’t use jQuery if you don’t need it elsewhere)

Without jQuery: https://stackoverflow.com/a/800010/8068675

Solution 2:

Try adding forward slash ‘/‘ while calling app.js file

<script src=”{ mix(‘/js/app.js’) }”></script>

The only reason is that the project is not getting proper app.js file’s path. You can debug by pressing ctrl+u and check the path of the js file.

[Vue.js] Vue should only trigger the clicked element Subscribe to RSS

I’m on my first vue.js project. there is a table with cells. When I double click a cell, to trigger a child component in that cell with updated or similar.

So far I’ve been doing that by sending props to it. It works. The problem is that when I double click a cell, the updated is triggered in all the child components. It can be triggered 100 or 1000 of times, just for a single cell to be “activated”.

Screenshot

Code and question

This code below is far from how my project looks like, but will still show the issue. Click on a button and all the cells will react to it, not just the one clicked.

I do understand why it happends. In my child component I output data that has been changed by the parent. Then all child components react on it. However, there is no need to trigger them all when they are not active.

How can I just trigger the updated of the item I’m clicking on?

Vue.component(‘v-child’, {
props: [‘item’, ‘active’],
updated() {
console.log(‘Clicked’);
},
template: `
<div>
{ item } { active }
</div>`
});

new Vue({
el: ‘#app’,
data: {
active: 0,
items: {
first: ‘1’,
second: ‘2’,
third: ‘3’,
a: ‘a’,
b: ‘b’,
c: ‘c’
},
message: ‘Hello Vue.js!’
},
methods: {
click(item) {
this.active = item;
console.log(this.active);
}
}
});
li {
list-style: none;
margin-bottom: 1rem;
}
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id=”app”>
<li v-for=”item in items”>
<button v-on:click=”click(item)”>Button</button>
<v-child :item=”item” :active=”active”></v-child>
</li>
</div>

Solution :

updated is called for every child because active has changed, so each child needs to be rendered.

There are 2 ways to achieve what you want:

Cause active to change only for the active item
Keep the code and add some verification to check if the child is the active one (Steven Spungin solution)

Example for solution #1

Vue.component(‘v-child’, {
props: [‘item’, ‘active’],
updated() {
console.log(‘Clicked’);
},
template: `
<div>
{ item.value } { item.count }
</div>`
});

new Vue({
el: ‘#app’,
data: {
active: 0,
items: {
first: {value:’1’, count:0},
second: {value:’2’, count:0},
third: {value:’3’, count:0},
a: {value:’a’, count:0},
b: {value:’b’, count:0},
c: {value:’c’, count:0}
},
message: ‘Hello Vue.js!’
},
methods: {
click(item) {
item.count++;
}
}
});
li {
list-style: none;
margin-bottom: 1rem;
}
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id=”app”>
<li v-for=”item in items”>
<button v-on:click=”click(item)”>Button</button>
<v-child :item=”item” :active=”active”></v-child>
</li>
</div>

Solution 2:

Add a watch to active and compare the active value to the item.

Vue.component(‘v-child’, {
props: [‘item’, ‘active’],
watch: {
active(value) {
if (value === this.item) {
console.log(‘Clicked:’ + value);
}
}
},
template: `
<div>
{ item } { active }
</div>`
});

new Vue({
el: ‘#app’,
data: {
active: 0,
items: {
first: ‘1’,
second: ‘2’,
third: ‘3’,
a: ‘a’,
b: ‘b’,
c: ‘c’
},
message: ‘Hello Vue.js!’
},
methods: {
click(item) {
this.active = item;
}
}
});
li {
list-style: none;
margin-bottom: 1rem;
}
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id=”app”>
<li v-for=”item in items”>
<button v-on:click=”click(item)”>Button</button>
<v-child :item=”item” :active=”active”></v-child>
</li>
</div>

[Vue.js] problem in redirecting in guarded route - Vue js Router Subscribe to RSS

there is this route in my vue.js router.js file .

routes: [{
path: “/“,
component: Home,
beforeEnter: (to, from, next) => {
if (!store.state.is_login) {
next(‘/login’)
}
next()
}
}]

I use beforeEnter option for redirecting user if store.state.is_login === true

first problem :
so when I enter the url in browser I will redirect to /login page. this is works fine. but when I click the logo button, this beforeEnter function is not working.
this is my button that uses :

<router-link to=”/“ class=”bp-logo”><Logo />home</router-link>

the second problem is :

is_login is in my store.state.is_login
when storing my token in the localStorage
user_info is in store.state.user

problem :

condition 1: if !is_login redirect to /login .

condition 2 : if token exists and !is_login => request to backend /user with token and get user_info and set is_login true.

condition 3 : if !is_login && !token redirect to /login

Solution :

You need to change the beforeEnter method to access the store instance. Rewrite like this:

beforeEnter: (to, from, next) => {
if (!this.$store.state.is_login) {
next(‘/login’)
}
next()
}

Solution 2:

I figured it out somehow. the first problem was when you render a route .then you are click for getting to that route again the function router.beforeEach not trigger. so I find another method in documentation.

routes: [{
path: “/“,
component: Home,
beforeEnter: isAuthenticated,
}]

and this is my custom function for handling both problems .

const isAuthenticated = (to, from, next) => {
if (!store.state.is_login) {
if ((localStorage.getItem(‘token’)) && (lodash.isEmpty(store.state.user))) {
let headers = {
headers: {
Authorization: localStorage.getItem(“token”),
“Access-Control-Allow-Origin”: “*“
}
};
axios
.get(`${store.state.api}admin/user`, headers)
.then(response => {
store.state.user = response.data.user;
store.state.is_login = true;
next(“/“);
})
.catch(error => {
store.state.Error = error;
next(‘/login’)
});
}
next(‘/login’)
return
}
next()
return
}

[Vue.js] Is there a way to disable default cursor placement when using VueJs? Subscribe to RSS

when creating a time input text field in which you override zeros with the time that you fill in. When removing the filled in numbers the numbers get replaced with zeros.

When changing the bound text the cursor gets moved to the end of the text and I set the cursor back to the place that it should be located with the setSelectionRange method.

when trying to disable the cursor placement to the end of the text so the cursor does not bounce around, however I cannot seem to find a way to disable this behaviour.

Can anybody help me to better understand the behaviour of the cursor and how I might be able to disable the movement of it?

I tried to create a time input field without the zeroes but whenever I fill in a number somewhere else then the last character I get a jumpy cursor.

In my example I add a one to the text field with every key press.
You can see the cursor moving to the end of the field before getting placed by the code.

[Fiddle] https://jsfiddle.net/Banthornes/c6zds1h4/1/

this.text = this.text + ‘1’

if(this.cursorLocation > 0)
{
this.cursorLocation -= 1
}

this.$refs.input.setSelectionRange(this.cursorLocation,
this.cursorLocation)

I tested this in the following browsers:
- Chrome
- Firefox
- Brave
- Edge

Solution :

When you call setSelectionRange, the input has not updated yet.

Put the call to setSelectionRange in a setTimeout. You might even get away with a $nextTick, but in these cases the setTimeout is usually more reliable.

setTimeout( ()=>{

if(this.cursorLocation > 0)
{
this.cursorLocation -= 1
}

this.$refs.input.setSelectionRange(this.cursorLocation,
this.cursorLocation)

}, 500 )

[Vue.js] Accessing parameter/dynamic URL property in router meta for dynamic page title? Subscribe to RSS

So there is for example this route in my routes:

{ name: ‘user’, path: ‘/user/:id’, component: User, props: { default: true, sidebar: false }, meta: { showFooter: false, title: `Viewing User ${route.params.id}` } }

I’m essentially wanting to access the id parameter of the URL, to set the title of the page, but I do not want to do it via the component.

Using ${route.params.id} returns undefined, is there an object I can access that will give me the same result? I’m relatively new to vue.js and Vue-router, so unsure if this is possible or not.

Maybe I should be setting this in the component, and if so I’m happy to learn why this is the better way to do it :)

Solution :

You can simplify this and just use a computed property in the component.

computed: {
title() { return `Viewing User ${this.$route.params.id}` }
}

If you want to abstract the implementation (for multiple components, etc), set the meta data in beforeRouteUpdate. Then you can access this.$route.

beforeRouteUpdate (to, from, next) {
// called when the route that renders this component has changed,
// but this component is reused in the new route.
// For example, for a route with dynamic params `/foo/:id`, when we
// navigate between `/foo/1` and `/foo/2`, the same `Foo` component instance
// will be reused, and this hook will be called when that happens.
// *** has access to `this` component instance. ***
},

-> has access to this component instance