link274 link275 link276 link277 link278 link279 link280 link281 link282 link283 link284 link285 link286 link287 link288 link289 link290 link291 link292 link293 link294 link295 link296 link297 link298 link299 link300 link301 link302 link303 link304 link305 link306 link307 link308 link309 link310 link311 link312 link313 link314 link315 link316 link317 link318 link319 link320 link321 link322 link323 link324 link325 link326 link327 link328 link329 link330 link331 link332 link333 link334 link335 link336 link337 link338 link339 link340 link341 link342 link343 link344 link345 link346 link347 link348 link349 link350 link351 link352 link353 link354 link355 link356 link357 link358 link359 link360 link361 link362 link363 link364 link365 link366 link367 link368 link369 link370 link371 link372 link373 link374 link375 link376 link377 link378 link379 link380 link381 link382 link383 link384 link385 link386 link387 link388 link389 link390 link391 link392 link393 link394 link395 link396 link397 link398 link399 link400 link401 link402 link403 link404 link405 link406 link407 link408 link409 link410

[Vue.js] How do i iterate through JSON in VueJS?

when storing some settings in the database with keys and JSON data but when I get these settings from a Laravel API, it returns an array which becomes a hectic work in reassigning data to the input fields. to know if there is an easier way of doing it.

So far there is tried iterating and using the switch statement to identify keys and reassign them. But the problem is I can’t access the VueJS data variable in the loop.

Here is a look at the database table:
Database Table

Here are the objects when using in Vue:

helpful_notification: {
email: false,
sms: false,
push: false,
},
updates_newsletter: {

email: false,
sms: false,
push: false,

},

Here is my Code to Iterate over results:

axios.get(‘/api/notificationsettings’)
.then(response => {
var data = response.data;
let list = [];
console.log(data)
$.each(data, function(i, j){
switch(j.key){
case ‘transactional’:

var settings = JSON.parse(j.settings)
var x = {
transactional : settings
}
list.push(x)
break;
case ‘task_reminder’:
var settings = JSON.parse(j.settings)
x = {
task_reminder : settings
}
list.push(x)
break;
}
});
this.transactional = list;
// this.task_reminder= list.task_reminder;
console.log(list);
})
.catch(error => {

});

Solution :

In JavaScript, functions have their own scope, save for a few exceptions. Which means that, inside the anonymous function (i.e:

$.each(data, function(i, j){
// this here is the function scope, not the outside scope
})

…), this is not the outside scope, it’s the function’s scope

There are two ways to make the outside scope available inside the function:

a) place it inside a variable

const _this = this;
$.each(data, function(i, j){
// this is function scope,
// _this is outside scope (i.e: _this.list.task_reminder)
})

b) use an arrow function

$.each(data, (i, j) => {
// this is the outside scope
// the arrow function doesn’t have a scope.
})

The above is a simplification aimed at helping you access the outside scope inside the function. But this can differ based on the context it is used in. You can read more about this here.

[Vue.js] How to filter an array in Vue.js with multiple select buttons?

I try to filter an object of array in Vue.js. have products collection in this vue.js component. I would like to filter this collection with select buttons. These products are food products and as default I would like to show all products but if I select the lactosefree button the I would like to show only products are lactosefree. In my database these options true or false. so for example if there is a cheese that lactose free then in the database there is a field lactosefree with value true.

there is tried to filter the array with computed property but I don’t really know how to do it.

<div class=”col-12 justify-content-between row filterbtn”>
<label class=”btn btn-primary”>
<input v-model=”selected” value=”gluteinfree” type=”checkbox” class=”check2”>GLUTEIN FREE
</label>

<label class=”btn btn-primary”>
<input v-model=”selected” value=”lactosefree” type=”checkbox” class=”check2”>LAKTOZ FREE
</label>
</div>

<script>
export default{
data(){
return{
products: [
{ “id”: 1, “productName”: “Majomkenyrfa kivonat”, “gluteinfree”: true, “lactosefree”: false, },
{ “id”: 2, “productName”: “Kkuszolaj”, “gluteinfree”: false, “lactosefree”: true,},
{ “id”: 3, “productName”: “C-vitamin 80mg”, “gluteinfree”: true, “lactosefree”: true, },
],
selected: [],
}
},

computed: {
//
},
}
</script>

As default I would like to show all the products. but when i click the gluteinfree select button I would like to show only the First and the last products where the gluteinfree is true.

Solution :

Here is the code you can use for the computed. This will loop over all the products and compare each against a list of selected options

return this.products.filter(product => this.selected.every(selection => product[selection] === true));

note that it’s using filter and every which for old browsers may require polyfills. You can can also convert to a more verbose for loop though.

Code:

new Vue({
el: ‘#app’,
data() {
return {
products: [{
“id”: 1,
“productName”: “Majomkenyrfa kivonat”,
“gluteinfree”: true,
“lactosefree”: false,
},
{
“id”: 2,
“productName”: “Kkuszolaj”,
“gluteinfree”: false,
“lactosefree”: true,
},
{
“id”: 3,
“productName”: “C-vitamin 80mg”,
“gluteinfree”: true,
“lactosefree”: true,
},
],
selected: [],
}
},
computed: {
zsir() {
return this.products.filter(prod => this.selected.every(sel => prod[sel] === true));
},
}
})
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id=”app”>
<div class=”col-12 justify-content-between row filterbtn”>
<label class=”btn btn-primary”>
<input v-model=”selected” value=”gluteinfree” type=”checkbox” class=”check2”>GLUTEIN FREE</label>
<label class=”btn btn-primary”><input v-model=”selected” value=”lactosefree” type=”checkbox” class=”check2”>LAKTOZ FREE</label>
</div>
<ul>
<li v-for=”prod in zsir” :key=”prod.id”>{prod.productName}</li>
</ul>
</div>

[Vue.js] How to replace HTML content of <span> tag with value of input field without setting the value of input

there is a message saying Hey There. I would like to replace the ‘There’ text with the value being typed in the input box.

I tried using directive

HTML

<div id=”updateName”>
<!–form sec–>
<section class=”animated container-fluid align-center sec-ptop”>
<h3 class=”salutation”>Hey <span>{inputName}There</span>, happy to hear from you.</h3>
<div>
<form name=”contactform” method=”post” class=”row form-horizontal” role=”form”>
<div class=”form-group input–josh col-sm-6”>
<div class=”input-wrap”>
<input autocomplete=”off” v-init type=”text” v-model=”inputName” class=”form-control input__field input input__field–josh” id=”inputName” name=”inputName” placeholder=”Name” value=”” required />
<label class=”input__label input__label input__label–josh input__label–josh-color-1 input__label–josh input__label–josh-color-1”></label>
</div>
</div>
</form>
</div>
</section>
</div>

vue

var app = new Vue({
el: ‘#updateName’,
data: {
inputName: ‘There’
},
directives: {
init: {
bind(el){
el.value = el.getAttribute(‘value’);
el.dispatchEvent(new Event(‘input’));
}
}
},
});

HTML

<div id=”updateName”>
<!–form sec–>
<section class=”animated container-fluid align-center sec-ptop”>
<h3 class=”salutation”>Hey <span>{inputName}There</span>, happy to hear from you.</h3>
<div>
<form name=”contactform” method=”post” class=”row form-horizontal” role=”form”>
<div class=”form-group input–josh col-sm-6”>
<div class=”input-wrap”>
<input autocomplete=”off” type=”text” v-model=”inputName” v-on:keyup.enter=”replaceText(inputValue)” class=”form-control input__field input input__field–josh” id=”inputName” name=”inputName” placeholder=”Name” required />
<label class=”input__label input__label input__label–josh input__label–josh-color-1 input__label–josh input__label–josh-color-1”></label>
</div>
</div>
</form>
</div>
</section>
</div>

vue

var app = new Vue({
el: ‘#updateName’,
data: {
inputName: ‘There’
},
methods: {
replaceText: function(inValue) {
this.inputName = this.inputName + inValue
}
}
});

On page load

Hey There, happy to hear from you.

Name

On run-time

Hey John, happy to hear from you.

John

On Run Time

Solution :

I’m not sure whether we can populate the form data while a form submit.

If you want to submit the form data then you have to prevent ( event.preventdefault ) the form data and saved it into another variable.

But if you no need to submit the form means you can achieve it by using my below sample code

<html>
<head>
<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type=”text/javascript” src=”https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>

<div id=’myApp’>
<h3 class=”myName”>Hey <span v-if=’inputName.length’>{inputName}</span> <span v-else>There</span>, happy to hear from you.</h3>
<form method=”post”>
<input autocomplete=”off” type=”text” v-model=”inputName” class=”form-control” id=”inputName” name=”inputName” placeholder=”Name” />
</form>

</div>

</body>
</html>
<script type=”text/javascript”>
var myInstance = new Vue({
el:’#myApp’,
data:{
inputName : ‘’
}

})
</script>

You have to do the same for the rest of the place you needed.

Solution 2:

You can remove the method because you use the ‘v-model’, which says that if the input changes, the data will change too.

You can also remove the span tag if you don’t need to change something on the name and remove the static ‘There’ in the span.

<h3 class=”salutation”>Hey <span>{inputName}</span>, happy to hear from you.</h3>

is the same as

<h3 class=”salutation”>Hey {inputName}, happy to hear from you.</h3>

Here’s a fiddle

Hope it works for you.

[Vue.js] Adding images to Vue Select dropdown?

when using vue-select component as my dropdowns and giving it :options as the data to put in the dropdown. when using it for a credit card dropdown right now and want to add the card type image in in each dropdown row. Is this possible?

Solution :

You could use the scoped option slot that vue-select provides for creating custom dropdown templates.

Assuming that the options data looked like this:

options: [
{
title: “Visa”,
cardImage: “https://codeclimate.com/github/sagalbot/linktoimage.png"
},
{
title: “Mastercard”,
cardImage: “https://codeclimate.com/github/sagalbot/linktoimage.png"
}
];

Then you could use it as such:

<v-select :options=”options” label=”title”>
<template slot=”option” slot-scope=”option”>
<img :src=”option.cardImage” />
{ option.title }
</template>
</v-select>

[Vue.js] Input cursor jumps to end of input field on input event

Im trying to convert the user input to uppercase on input event

so, whenever I type a key in the input field Im facing the following issues

The cursor jumps to end of the input value when user types in the middle.
the last typed character (not the last character) is not converting to uppercase.

Here is the link to JS fiddle https://jsfiddle.net/aeL051od/ to reproduce the issue

new Vue({
el: “#app”,
data() {
return {
input: null
}
},
methods: {
handleInput(e) {
this.input = e.target.value ?
e.target.value.toString().toUpperCase() :
e.target.value;
}
}
});
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id=”app”>
<input type=”text” v-model=”input” @input=”handleInput”> { input }
<!– { input } is just for reference –>
</div>

Solution :

If you (or Vue) copy a new value into an input, the cursor will be set to the end of the input. If you want to retain the previous position, you will need to capture the position, make the change, then on the $nextTick restore the position.

Also note that if you are going to set this.input in the handler, there’s no point in the using v-model, too. It’s also unlikely that saving the event is sensible, but you can.

new Vue({
el: “#app”,
data() {
return {
input: null,
event: null
}
},
methods: {
handleInput(e) {
const el = e.target;
const sel = el.selectionStart;
const upperValue = el.value.toUpperCase();

el.value = this.input = upperValue;
this.event = e;
this.$nextTick(() => {
el.setSelectionRange(sel, sel);
});
}
}
});

#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}

input {
margin-bottom: 20px;
}
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id=”app”>
<input type=”text” @input=”handleInput”>
<p>{ event ? event.target.value : null }</p>
<p>
{input}
</p>
</div>

Solution 2:

{ event ? event.target.value : null } here you display target value.

you have to display converted input value. The should be like below

<div id=”app”>
<input type=”text” v-model=”input” @input=”handleInput”>
<p>{ input }</p>
</div>

for Cursor Jump issue get the position of the cursor on start then after update value set back cursor to start position

handleInput(e) {
var start = e.target.selectionStart;
this.input = this.input.toUpperCase()
this.$nextTick(()=>{
e.target.selectionStart = e.target.selectionEnd = start;
})
}

Fiddle : https://jsfiddle.net/r53ecug6/

Solution 3:

I was able to solve the issue but you need to introduce a new variable in the code

HTML:

<div id=”app”>
<input type=”text” v-model=”input” @input=”handleInput”>
<p>{ updated_value }</p>
</div>

JS:

new Vue({
el: “#app”,
data() {
return {
input: null,
updated_value: null
}
},
methods: {
handleInput(e) {
this.input = e.target.value;
this.updated_value = e.target.value ? e.target.value.toString().toUpperCase()
: e.target.value;
}
}
});

Link to fiddle

Summary:
1) Use a new variable (updated_value) to store the uppercase version of the input and use that as the value for <p>
2) This ensures that the input value is not updated , thus not causing the issue of the cursor to jump

[Vue.js] How to call script on template condition in Vue

there is a template conditional like this in my vue.js template:

<div class=”search__container”>
<div v-if=”!init”>
<spinner/>
</div>
<div class=”search__content-container” v-else-if=”results.length > 0”>
<div class=”search__facets-container”>
<menu></menu>
</div>
<div class=”search__results-container”>
<results></results>
</div>
</div>
<div v-else class=”search__no-results”>
<div v-html=”noResultsTxt”></div><br>
<v-btn href=”/“ color=”white” class=”grey–text grey–border search__continue-btn”>{ continueText }</v-btn>
<div id=”suggested-products”></div>

// How do I run this here?
<script>loadSuggestions();</script>
</div>
</div>

The loadSuggestions() call is the bit I can’t get to work. It should only run if and when the .search__no-results div is shown. I’m guessing I may need to create a watcher with the same conditional logic to achieve this, but that seems overly complex given I already of the logic in my template.

Any thoughts on the best pattern to use here?

Solution :

You can create a component inside the search__no-results, then you call the loadSuggestions() in the mounted or created hook.

OR

computed() {
noResult() {
return this.init && this.results.length <= 0;
},
},
watch: {
noResult(noResult) {
if (noResult) {
this.loadSuggestions();
}
}
}

[Vue.js] v-model concatenate a string with a var?

I’ve read answers such as this but can’t get my template to compile.

I need to concatenate a string with a var in v-model to bind to an array inside an object:

<li v-for=”name in names”>
<input type=”checkbox” v-model=”‘checked.’+name”>
….

I just get a compile error though.

Also when I do this:

:data-test=”‘checked.’+name”

It compiles fine, so its something with v-model.

The compile error is:

Syntax Error: SyntaxError: Unexpected token (1:1161)

Solution :

Just in case a slightly different perspective helps: Whether you use it in a v-model or :data-test directive

‘checked.’+name

results in a string. Although it probably isn’t what one would normally want to do, that is syntactically legal for an arbitrary v-bind (e.g. :data-test). That is not, however, syntactically legal for a v-model. As other have pointed out, v-model attempts to assign a value on “change” events. It would be equivalent, for example, to

‘checked.foo’ = true;

when what I think you want is

checked.foo = true;

It’s hard to say for sure without seeing more of the code, but it may be the case that

<input type=”checkbox” v-model=”checked[name]“>

is sufficient for you.

Solution 2:

The v-model=”name” helps you do two things.

:value=”name”
@input=”name = $event

However, in the case, you’re doing v-model=”‘checked.’+name”, which means:

:value=”‘checked.’+name” // which is perfectly fine
@input=”‘checked.’+name = $event” // this would cause an error.

Documentation can be found here.

Below are some solution of mine: JsFiddle

computed: {
checkedName: {
// getter
get: function () {
return `${this.prefix}${this.name}`;
},
// setter
set: function (newValue) {
this.name = newValue.replace(this.prefix, ‘’);
}
}
},

then

<input type=”checkbox” v-model=”checkedName”>

Solution 3:

You can’t do that.

v-model is used for two-way data binding and is a syntactic sugar for :checked=”myField” + @change=”evt => myField = evt.target.checked in the case of a checkbox.

As you can see, myField must be a valid left-hand side expression in JS, this is by the way one of the rules precised by vue.js to have a valid v-model:

The directive does not have the attribute value which is valid as LHS. E.g. <input v-model=”foo() + bar()”>

And that is exactly why the template doesn’t compile. vue.js can understand how to bind the data in one way because it can assign ‘checked.’+name to a variable, but it can’t assign a variable to ‘checked.’+name - that is not a valid left-hand sign expression.

[Vue.js] Cant pass parameter from store vuex in api call using router

I try to fetch data with axios get with parameter that come from vuex store.
Problem is i get parameter undefined altought is in the store

data() {
return {
payments: [],
destinations: [],
};
},
computed: {
codcli() {
return this.$store.getters.codcli;
},
total() {
return this.$store.getters.orderTotal;
}
},
methods: {
setData(payments, destinations) {
this.payments = payments;
this.destinations = destinations;
}
},
beforeRouteEnter(to, from, next) {
axios
.all([
axios.get(`/api/payments/${this.codcli}/${this.total}`),
axios.get(`/api/getcustomerdestinations/${this.codcli}`)
])
.then(
axios.spread((payments, destinations) => {
next(vm => vm.setData(payments.data, destinations.data));
console.log(payments.data, destinations.data);
})
.catch(error=> console.log(error))
);
}

what’s going on here? what i mess? cant understand because the getters of vuex works

Solution :

The component’s instance has not been created yet when
beforeRouteEnter is executed and that is why you don’t have access to
this.

Taken from the official docs:

beforeRouteEnter (to, from, next) {
// called before the route that renders this component is confirmed.
// does NOT have access to `this` component instance,
// because it has not been created yet when this guard is called!
},

One possible solution to this is by importing the main store file in this component and using it directly for accessing the getters instead instead of using the computed properties.

Assuming that this component and the store file exists in the same root folder level:

import store from “./store”;

And access the getters like this:

beforeRouteEnter (to, from, next) {
const codcli = store.getters.codcli;
const total = store.getters.orderTotal;
axios
.all([
axios.get(`/api/payments/${codcli}/${total}`),
axios.get(`/api/getcustomerdestinations/${codcli}`)
])
.then(
axios.spread((payments, destinations) => {
next(vm => vm.setData(payments.data, destinations.data));
console.log(payments.data, destinations.data);
})
.catch(error=> console.log(error))
);
},

[Vue.js] How do you get the value of a data attribute in a component in another component without using event bus?

there is a data attribute ‘auth’, which holds whether the user is logged in or not. If it is empty then the user is not logged in, if it has ‘loggedin’ in it then the user is logged in.

This is in one component called ‘App.vue’ and there is another component called ‘DashboardComponent.vue’. If the user isn’t authenticated, but types in ‘/dashboard’ URL, the app to kick the user back to the login screen. How do i get the ‘auth’ data from the ‘App.vue’ component into the ‘DashboardComponent.vue’ and check if the user is authenticated (before the dashboard renders)?

EDIT:

This is how im currently trying to do it

[DashboardComponent]
EventBus.$on(‘logged-in’, status => {
this.auth = status
})

beforeMount () {
if (this.auth !== ‘loggedin’) {
router.push({name: ‘login’})
}
}

Is this the correct method? If so, why is it not working?

Solution :

Declare the data into main file where vue.js initializes like

window.App = new Vue({
el: ‘#app’,
router,
components: { App },
data: function(){
return {
auth:’’
}
}

})

after that you may change it in main file as

mounted:function(){
//when logged in then change status
this.status = ‘loggedIn’
}

Now access it in any component using App.status

[Vue.js] Laravel/Vue JS - Cannot upload files from Android devices

there is a Laravel/vue.js JS web app in which users are able to upload files and photos. Everything works fine until I try it in Android devices, where the axios call just hangs forever. Here’s my code:

vue.js JS component

<template>
<span>
<v-btn @click=”pickFile”>
<small>{ label }</small>
</v-btn>
<input type=”file” style=”
visibility:hidden;visibility: hidden;
position: absolute;
width: 1px;
height: 1px;
left: 0;
right: 0;”
ref=”upload” :accept=”accept” @change=”onFilePicked”> // accept is defined in the element’s props
</span>
</template>

vue.js JS components’ methods

methods: {
pickFile() {
this.$refs.upload.click()
},
onFilePicked (e) {
const files = e.target.files
let elem = this
let valid = true
Event.$emit(‘uploading’)
if(files[0] !== undefined) {
elem.fileName = files[0].name
if(elem.fileName.lastIndexOf(‘.’) <= 0) {
return
}

const fr = new FileReader ()
fr.readAsDataURL(files[0])

fr.addEventListener(‘load’, () => {
let formData = new FormData();
formData.append(‘file’,files[0]);
formData.append(‘document’,elem.document);
formData.append(‘pedido’,elem.pedido);

console.log(formData)

axios.post(‘/files/upload-file’,formData, { headers: {‘Content-Type’: ‘multipart/form-data’})
.then(response => {
//console.log(response);
Event.$emit(‘fileUploaded’, response.data.filepath);
Event.$emit(‘alert’, ‘Tu archivo se guard exitosamente’);
});
});
} else {
elem.fileName = ‘’
}
}
},

In the backend, I use the Input, Storage and File facades to write to the disk, and save a FileEntry to my database. This whole process works perfectly fine on computers and iOS mobile devices, is there any special consideration for Android I’m missing?

Solution :

I found the actual reason, it had nothing to do with the Android devices as much as with the size of the file being uploaded. I added the proper php.ini configuration and will proceed to compress images on the fly.