link3151 link3152 link3153 link3154 link3155 link3156 link3157 link3158 link3159 link3160 link3161 link3162 link3163 link3164 link3165 link3166 link3167 link3168 link3169 link3170 link3171 link3172 link3173 link3174 link3175 link3176 link3177 link3178 link3179 link3180 link3181 link3182 link3183 link3184 link3185 link3186 link3187 link3188 link3189 link3190 link3191 link3192 link3193 link3194 link3195 link3196 link3197 link3198 link3199 link3200 link3201 link3202 link3203 link3204 link3205 link3206 link3207 link3208 link3209 link3210 link3211 link3212 link3213 link3214 link3215 link3216 link3217 link3218 link3219 link3220 link3221 link3222 link3223 link3224 link3225 link3226 link3227 link3228 link3229 link3230 link3231 link3232 link3233 link3234 link3235 link3236 link3237 link3238 link3239 link3240 link3241 link3242 link3243 link3244 link3245 link3246 link3247 link3248 link3249 link3250 link3251 link3252 link3253 link3254 link3255 link3256 link3257 link3258 link3259 link3260 link3261 link3262 link3263 link3264 link3265 link3266 link3267 link3268 link3269 link3270 link3271 link3272 link3273 link3274 link3275 link3276 link3277 link3278 link3279 link3280 link3281 link3282 link3283 link3284

[Vue.js] How to use `new google.maps.Marker()` with `vue2-google-maps`

For some reasons, there is to use new google.maps.Marker() with vue2-google-maps, but I don’t know how to start since the documents and many people use <GmapMarker … /> in the HTML part instead.

I’ve tried to search but the document doesn’t cover this.

Right now my code looks like this, it doesn’t have any error but it doesn’t work either (the map is present but the marker isn’t shown):

<template>
<div style=”height: 100%; width: 100%;”>
<GmapMap
:center=”{ lat: 0, lng: 0 }”
ref=”mapRef”
\>
</GmapMap>
</div>
</template>

<script>
import * as VueGoogleMaps from ‘vue2-google-maps’;

export default {
computed: {
google: VueGoogleMaps.gmapApi,
},
methods: {
init() {
new this.google.maps.Marker({
position: {
lat: 0,
lng: 0
},
map: this.$refs.mapRef,
});
}
},
async mounted() {
this.init()
},
}
</script>

Solution :

Ok, I figured out. Here’s what I did:

Create a map variable in data()

data() {
return {
map: undefined,
}
},

Set it using this function in mounted()

mounted() {
this.$refs.mapRef.$mapPromise.then((map) => {
this.map = map;
this.init();
});
},

Now, Bob’s the uncle, you can use this.map where ever you want

methods: {
init() {
new this.google.maps.Marker({
position: {
lat: 0,
lng: 0
},
map: this.map,
});
},
}

[Vue.js] Vue JS display table row once

I’m unable to figure out how to loop through the array in the code I’m working on.

the table row to display once not thrice.

new Vue({
el: ‘#app’,
data: {
a: {
b:[
{ c: [ {d: “1”}, {d: “2”}, {d: “3”} ] },
{ c: [ {d: “1”}, {d: “2”}, {d: “3”} ] },
{ c: [ {d: “1”}, {d: “2”}, {d: “3”} ] }
]
}
}
})
<script src=”https://unpkg.com/vue"></script>

<div id=”app”>
<table>
<thead>
<tr v-for=”b in a.b”>
<th v-for=”c in b.c”>{c.d}

</th>
</tr>
</thead>
</table>
</div>

https://jsfiddle.net/xe8w1q4u/

Solution :

Well, if you just want to display the first row:

new Vue({
el: ‘#app’,
data: {
a: {
b:[
{ c: [ {d: “1”}, {d: “2”}, {d: “3”} ] },
{ c: [ {d: “1”}, {d: “2”}, {d: “3”} ] },
{ c: [ {d: “1”}, {d: “2”}, {d: “3”} ] }
]
}
}
})
<script src=”https://unpkg.com/vue"></script>

<div id=”app”>
<table>
<thead>
<tr v-if=”a.b.length > 0”>
<th v-for=”c in a.b[0].c”>
{c.d}
</th>
</tr>
</thead>
</table>
</div>

[Vue.js] how to update the height of a textarea in vue.js when updating the value dynamically?

Working with Vue.js, I do use a simple way to set dynamically the height of a text area that resizes when typing. But when not able to do it when the component mounts or the value updates.

there is already try http://www.jacklmoore.com/autosize/, but it has the same problem.

there is created a sandbox that shows the problem, when typing the box it updates, but not when the value changes dynamically

Live example: https://codesandbox.io/s/53nmll917l

Solution :

You need a triggerInput() method:

triggerInput() {
this.$nextTick(() => {
this.$refs.resize.$el.dispatchEvent(new Event(“input”));
});
}

to use whenever you’re changing the value programatically, triggering the resize logic used on <textarea> on “real” input events.

Updated codesandbox.

Note: Without the $nextTick() wrapper, the recently changed value will not have been applied yet and, even though the input is triggered, the element has not yet been updated and the resize happens before value has changed, resulting in the old height and looking like it didn’t happen.

[Vue.js] vue.js custom css for a component (Without webpack and vue-loader)

Using vue.js Router to load the components.

Note that when not using webpack or vue-loader.

Here is a sample component that get loaded by vue.js - router

export default {
name: ‘Abc’,
template:’<div>Now .. i can’t add style element here :(. So where should i add it </div>’,
data(){
return {
message:’ new message’
}
},
}

Where can i add css styles. I don’t care about css scoped if it is not possible.

Solution :

You can use any CSS library like Bootstrap, Bulma etc, and add css classes directly in template like the following.

In head section of the page add bootstrap reference link and that’s it.

template: `<div class=”container”>Boostrap</div>`

[Vue.js] VueJS <input> value change not calling @change

With VueJS, there is two seperate components.

A modal and a form.

In the modal form, the user inputs a PIN that gets confirmed then this value is set to an input tag in the form to basically save this value.

In the modal component, I set the value simply like this:

document.getElementById(‘pin’).value = this.pin_input;

Within the form component, the input tag is like this:

<input type=”hidden” @change=”submit()” id=”pin”>

In the console, the value of this input tag get’s set correctly, though the @change=”submit()” is not getting called when the values changes.

submit method code within form component that is not getting called:

methods : {
submit : function(){
console.log(“SUBMIT HERE”);
}
}

Why is my input tag’s @change not getting called?

Solution :

From my point of view, For communication between components it’s better to use:

some state management like Vues https://vuex.vuejs.org/, and save input value in separate store
or
try with custom methods https://vuejs.org/v2/guide/components-custom-events.html
use parent component and pass callback into child components.

@change will not work in the case

Solution 2:

Setting the value on a DOM element does not fire the input / change events. This is why the event listener you set in vue.js is not called.

You can fire those events manually, they will then be picked up by vue.

var element = document.getElementById(‘pin’);
element.value = this.pin_input;
// Works in most modern browsers.
var event = new Event(‘change’);
element.dispatchEvent(event);

[Vue.js] Reflect and make Axios request in the browser's URLWhat I'm looking forProblemSolution

What I’m looking for

Bit of JavaScript logic help; although, when not sure what I will need to do via vue.js Router. Not looking exactly for the answer, but more pointed in the right direction (I’m not even sure I’m phrasing this question correctly).

Problem

there is been making API requests with Axios (no problem there). there is a JWT token in the requests headers. However, (never done this before) I now need to have the search params the user entered in the browsers URL when they make a request to share the link to their coworkers which will route to the same page with the same options entered/selected and the API request called with those query params.

What I really dont know is:

A. Whats the best way to make an API request on route (loading the url with query params)? The route of the page does NOT match the corresponding API endpoint Url.
B. How do I get the users entered/selected data into the browsers URL?
C. Do I need to modify my route objects for those pages to still route correctly even if there is now a query string?

Solution

(Must be purely a frontend solution - Im using the whole vue.js ecosystem)

Solution :

Figured out what I need to do:

A

The project is not server-side rendered; therefore, I need to parse the URL on Vue’s created and make a request with the params in the query string. This will seem like the URL caused a API request.

B

Simply append Axios’ request query string to the URL, which I believe is cosmetic and should be fine.

C

I’m not sure, but will play around with it.

[Vue.js] Selecting a radio button does not trigger @input

I having a problem with a radio-group in a child component of a larger form, all presented through the Vuetify framework.

I cannot get the radio-group to trigger an @input event whenever any of its options are selected. The selected radio value is emitted when I change the value in the Results text area.

The problem remains if I abandon the Vuelidate involvement and set the model in the radio group to v-model=”form.sourceid”.

My code is:

<template>
<form @input=”submit” class=”form”>
<v-card-text>
<v-radio-group
label=”Risk type”
:mandatory=”false”
v-model=”$v.form.sourceid.$model”
\>
<v-radio
v-for=”risk in risks”
:key=”risk.value”
:label=”risk.label”
:value=”risk.riskId”
:checked=”risk.riskId == form.sourceid”
color=”teal”
\></v-radio>
</v-radio-group>
<v-text-field
v-model.trim=”form.results”
type=”text”
label=”Results”
box
\></v-text-field>
</v-card-text>
</form>
</template>

<script>
import {required} from ‘vuelidate/lib/validators’

const FORM_TEMPLATE = {
sourceid: null,
results: null,
}
export default {
props: {
wizardData: {
type: Object,
required: true
}
},
data() {
return {
form: {…FORM_TEMPLATE, …this.wizardData},
risks: [
{ label: ‘Soil’,riskId: ‘1’},
{ label: ‘Water’,riskId: ‘2’},
{ label: ‘Agrichemicals’,riskId: ‘3’},
]
}
},
validations: {
form: {
sourceid: {
required
},

}
},
methods: {
submit () {
this.$emit(‘update’,
{ data: this.form,
valid: !this.$v.$invalid
}
)
},
}
}
</script>

The contents of wizardData when using a ‘clean form’ are:

{
“sourceid”: null,
“results”: null
}

My submit method is:

submit () {
this.$emit(‘update’,
{ data: this.form,
valid: !this.$v.$invalid //this line removed if testing without Vuelidate
}
)
},

Any assistance muchly appreciated.
Thanks, Tom

Solution :

The solution was to read the docs with both eyes open and discover that radio buttons respond to the change event.

So, altering the v-radio-group attributes to read the following solved my problem:

<v-radio-group
label=”Risk type”
v-model=”$v.form.sourceid.$model”
:mandatory=”false”
@change=”submit”
\>

Cheers, Tom

[Vue.js] Register component doesn't insert data. Throws new MethodNotAllowedHttpException($others);

I’m trying to post user register data to my db using axios.post from Register.vue.js component. but this gives me an error. I don’t know if the error is on the form or on the inputs.

This is my Register.vue

<template>
<div class=”login-wrapper border border-light”>
<form action=”” method=”post” enctype=”multipart/form-data” class=”form-horizontal”>
<h2 class=”form-signin-heading”>Please sign in</h2>
<div class=”form-group”>
<label for=”usuario” class=”sr-only”>Username</label>
<input v-model=”usuario” type=”usuario” id=”inputEmail” class=”form-control” placeholder=”Username” required autofocus>
<label for=”inputEmail” class=”sr-only”>Email </label>
<input v-model=”email” type=”email” id=”inputEmail” class=”form-control” placeholder=”Email address” required autofocus>
<label for=”inputPassword” class=”sr-only”>Password</label>
<input v-model=”password” type=”password” id=”inputPassword” class=”form-control” placeholder=”Password” required>
<button class=”btn btn-primary” @click=”registrarUsuario()”>Register</button>
</div>
</form>
</div>
</template>

<script>
export default {
data () {
return {
usuario: ‘’,
email: ‘’,
password: ‘’,
errorPersona : 0,
errorMostrarMsjPersona : [],
}
},
methods: {

registrarUsuario(){
console.log(this.email);
if (this.validarUsuario()){
return;
}

let me = this;
axios.post(‘/user/registrar’,{
‘email’ : this.email,
‘usuario’: this.usuario,
‘password’: this.password
}).then(function (response) {
console.log(“3”);
}).catch(function (error) {
console.log(“4”);
console.log(error);
});
},

validarUsuario(){
console.log(“2”);
this.errorPersona=0;
this.errorMostrarMsjPersona =[];
if (!this.email) this.errorMostrarMsjPersona.push(“El correo de usuario no puede estar vaco.”);
if (!this.usuario) this.errorMostrarMsjPersona.push(“El nombre de usuario no puede estar vaco.”);
if (!this.password) this.errorMostrarMsjPersona.push(“El password no puede estar vaco.”);
if (this.errorMostrarMsjPersona.length) this.errorPersona = 1;
return this.errorPersona;
},
}
}
</script>

This is my UserController.php

public function store(Request $request)
{
if (!$request->ajax()) return redirect(‘/‘);

DB::beginTransaction();
$usuario = new User();
$usuario-> usuario = $request->usuario;
$usuario-> password = bcrypt($request->password);
$usuario-> condicion = 1;
$usuario->save();
console.log(‘end’);

DB::commit();
}

This is my web.php

Route::get(‘/main’, function () {
return view(‘contenido/contenido’);
})->name(‘main’);

//Route::resource(‘proyecto’, ‘ProyectoController’, [‘except’ => ‘show’]);

Route::get(‘/user’, ‘UserController@index’);
Route::post(‘/user/registrar’, ‘UserController@store’);
Route::put(‘/user/actualizar’, ‘UserController@update’);
Route::put(‘/user/desactivar’, ‘UserController@desactivar’);
Route::put(‘/user/activar’, ‘UserController@activar’);

Route::get(‘/register’,’Auth\RegisterController@showRegisterForm’);

Solution :

You must need csrf token or disable it.

First for disable

Http/Middleware/VerifyCsrfToken.php

protected $except = [
‘/user/registrar’
];

Second for send with csrf the ftemplate

<template>
<div class=”login-wrapper border border-light”>
<form action=”” method=”post” enctype=”multipart/form-data” class=”form-horizontal”>
{ csrf_field() }

<h2 class=”form-signin-heading”>Please sign in</h2>
<div class=”form-group”>
<label for=”usuario” class=”sr-only”>Username</label>
<input v-model=”usuario” type=”usuario” id=”inputEmail” class=”form-control” placeholder=”Username” required autofocus>
<label for=”inputEmail” class=”sr-only”>Email </label>
<input v-model=”email” type=”email” id=”inputEmail” class=”form-control” placeholder=”Email address” required autofocus>
<label for=”inputPassword” class=”sr-only”>Password</label>
<input v-model=”password” type=”password” id=”inputPassword” class=”form-control” placeholder=”Password” required>
<button class=”btn btn-primary” @click=”registrarUsuario()”>Register</button>
</div>
</form>
</div>
</template>

UPDATE

You can get csrf token from app.blade.php

var csrfToken = $(‘meta[name=”csrf-token”]‘).attr(‘content’);

Then update the axios.post request

axios.post(‘/user/registrar’,{
‘email’ : this.email,
‘usuario’: this.usuario,
‘password’: this.password
},headers: {
‘X-Requested-With’: ‘XMLHttpRequest’,
‘X-CSRFToken’: csrfToken,
}).then(function (response) {
console.log(“3”);
}).catch(function (error) {
console.log(“4”);
console.log(error);
});

[Vue.js] vue.js load script from cdn and then component vue (without webpack)

How can i load the custom script from cdn in the component. So that i can use myScript.abc() in the load method.

Vue.component(‘example’, {

// LOAD ANOTHER SCIPT : SAY cdn.myScript

// render function as alternative to ‘template’
render: function (createElement) {
return createElement(
// {String | Object | Function}
// An HTML tag name, component options, or function
// returning one of these. Required.
‘h2’,
// {Object}
// A data object corresponding to the attributes
// you would use in a template. Optional.
{
style: {
color: ‘red’,
},
domProps: {
innerHTML: ‘My Example Header’
}
},

)},
methods:{
a:function(z){
myScript.hello();
}
}
});

This is loaded via vue-router.
And not using vue-loader or webpack

How to load my custom script.
Any link to documentation will be helpful.

Solution :

This should do it:

beforeMount(){
this.scriptLoader(‘some/url’).then(() => {
this.a();
}, error => {
console.error(‘Failed to load script’, error.target.src)
})
},
methods:{
a:function(){
myScript.hello();
}
scriptLoader: function(url) {
return new Promise((resolve, reject) => {
const existing = document.querySelector(‘script#someUniqueId’);
if (existing) existing.remove();
const script = document.createElement(‘script’);
script.onload = () => {
resolve();
};
script.onerror = e => {
reject(e);
};
script.id = ‘someUniqueId’;
script.async = true;
script.src = url;
document.head.appendChild(script);
})
}
}

Let’s try it out…

Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
el: ‘#app’,
beforeMount() {
this.scriptLoader(‘https://vincentgarreau.com/particles.js/assets/\_build/js/lib/particles.js').then(() => {
this.a();
}, e => console.error(‘Failed to load script’, e.target.src))
},
methods: {
a: function() {
particlesJS(“particles-js”, {
particles: {
number: {
value: 80,
density: {
enable: true,
value_area: 840
}
},
color: {
value: “#ffffff”
},
shape: {
type: “triangle”,
stroke: {
width: 0,
color: “#000000”
},
polygon: {
nb_sides: 42
},
},
opacity: {
value: 0.42,
random: false,
anim: {
enable: false,
speed: 1,
opacity_min: 0.1,
sync: false
}
},
size: {
value: 3,
random: true,
anim: {
enable: false,
speed: 42,
size_min: 0.1,
sync: false
}
},
line_linked: {
enable: true,
distance: 210,
color: “#ffffff”,
opacity: 0.42,
width: 1
},
move: {
enable: true,
speed: 4.2,
direction: “none”,
random: true,
straight: false,
out_mode: “out”,
bounce: false,
attract: {
enable: false,
rotateX: 600,
rotateY: 1200
}
}
},
interactivity: {
detect_on: “canvas”,
events: {
onhover: {
enable: true,
mode: “repulse”
},
onclick: {
enable: true,
mode: “push”
},
resize: true
},
modes: {
grab: {
distance: 420,
line_linked: {
opacity: 1
}
},
bubble: {
distance: 420,
size: 42,
duration: 2.1,
opacity: 8.4,
speed: 3
},
repulse: {
distance: 84,
duration: 0.84
},
push: {
particles_nb: 4.2
},
remove: {
particles_nb: 2.1
}
}
},
retina_detect: true
});
},
scriptLoader: function(url) {
return new Promise((resolve, reject) => {
const existing = document.querySelector(‘script#particlesJs’);
if (existing) {
existing.remove();
}
const script = document.createElement(‘script’);
script.onload = () => {
resolve();
};
script.onerror = e => {
reject(e);
}
script.id = ‘particlesJs’;
script.async = true;
script.src = url;
document.head.appendChild(script);
})
}
}
})
body {
margin: 0;
background-color: #212121;
min-height: 100vh;
}

#particles-js {
position: absolute;
height: 100%;
width: 100%;
}
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id=”app”>
<div id=”particles-js”></div>
</div>

And with an error:

Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
el: ‘#app’,
beforeMount() {
this.scriptLoader(‘//some/bogus/link/particles.js’).then(() => {
this.a();
}, e => console.error(‘Failed to load resource from’, e.target.src))
},
methods: {
a: function() {},
scriptLoader: function(url) {
return new Promise((resolve, reject) => {
const existing = document.querySelector(‘script#particlesJs’);
if (existing) {
existing.remove();
}
const script = document.createElement(‘script’);
script.onload = () => {
resolve();
};
script.onerror = e => {
reject(e);
}
script.id = ‘particlesJs’;
script.async = true;
script.src = url;
document.head.appendChild(script);
})
}
}
})
body {
margin: 0;
background-color: #212121;
min-height: 100vh;
}

#particles-js {
position: absolute;
height: 100%;
width: 100%;
}
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id=”app”>
<div id=”particles-js”></div>
</div>

Note on if (existing) existing.remove();

This guards against appending the same <script> multiple times.
In many cases, where the resource doesn’t expire (or the expiry is irrelevant), you might want to skip script reload if it was already appended. i.e.: if(!existing) { /* append the script */ }.

By removing the previously appended <script> and adding it again we’re passing the expiry evaluation to the browser and, subsequently, to the server serving the resource.

If the resource has not expired, the browser will serve it from cache, without making a new request to the server.
If it expired, it will be requested again and the updated version will be served (useful when dealing with volatile resources).

I’d be tempted to move this method from a vue.js component into a service and import it where needed, rather than have it defined in each instance of that particular component.

[Vue.js] Dynamic refs inside v-for loop giving error don't appear in DOM. **Provided element is not within a Document**

when using canvas2Html where you i pass the ref of element to take image of element. when dynamically assigning the refs to take image of particular divs. The code runs but when getting the Provided element is not within a Document. In Devconsole refs are not appearing too.
when really stuck on this one. Any suggestions

https://codesandbox.io/embed/rlo3mmo5zp?fontsize=14

the image of signature and initial as output. when currently getting error. :/

Solution :

Do not forget that if you use :ref inside v-for then it becomes an Array - so you should change the code

async takeimage(name) {
let el = this.$refs[name][0]; // <— use an Array