link2329 link2330 link2331 link2332 link2333 link2334 link2335 link2336 link2337 link2338 link2339 link2340 link2341 link2342 link2343 link2344 link2345 link2346 link2347 link2348 link2349 link2350 link2351 link2352 link2353 link2354 link2355 link2356 link2357 link2358 link2359 link2360 link2361 link2362 link2363 link2364 link2365 link2366 link2367 link2368 link2369 link2370 link2371 link2372 link2373 link2374 link2375 link2376 link2377 link2378 link2379 link2380 link2381 link2382 link2383 link2384 link2385 link2386 link2387 link2388 link2389 link2390 link2391 link2392 link2393 link2394 link2395 link2396 link2397 link2398 link2399 link2400 link2401 link2402 link2403 link2404 link2405 link2406 link2407 link2408 link2409 link2410 link2411 link2412 link2413 link2414 link2415 link2416 link2417 link2418 link2419 link2420 link2421 link2422 link2423 link2424 link2425 link2426 link2427 link2428 link2429 link2430 link2431 link2432 link2433 link2434 link2435 link2436 link2437 link2438 link2439 link2440 link2441 link2442 link2443 link2444 link2445 link2446 link2447 link2448 link2449 link2450 link2451 link2452 link2453 link2454 link2455 link2456 link2457 link2458 link2459 link2460 link2461 link2462 link2463 link2464 link2465

[Vue.js] Prevent enter action on IOS return click

there is problems with IOS return key on keyboard (in Safari on iphone for example).
when using vue.js js in my web application where there is textarea in chat component:

<textarea
class=”field-text__input field-text__input–height-small field-text__input–max-height”
rows=”1”
ref=”messageField”
placeholder=”the message”
@keydown.enter.exact.prevent=”send”
@keyup.enter.ctrl.exact=”expandTextarea”
:value=”messageText”
@input=”updateMessage”>
</textarea>

On desktop browser or android devices message is sent on “Enter” click. But on IOS click on “return” key on keyboard also send message.
How I can prevent this action for IOS “return” key?
Thanks for any help.

Solution :

You would have to create some custom logic inside the send function in order to catch and return(quit) the function if you detect that it is an iOS device.

This stackOverflow answer is a great place for inspiration for sniffing user agens (What the device tells you it is)

[Vue.js] What's the proper way to inform users to refresh the browser on a SPA website (when .js files are changed)

I’m looking for a proper way to inform users about an updated website version.

Whenever I upload new production .js files some parts of the website still works properly without refreshing the browser, but most doesn’t and users might never figure out to just refresh the browser.

How can I give an automatic notice for users to refresh the browser, whenever new .js files are uploaded?

I’m using vue.js and Laravel-mix.

Solution :

A cache buster is required and can be automated with eg. gulp-rev: the concept is to rename resource files at each build, so that they won’t be retrieved from cache when the user opens the app.

But it’s not sufficient if the browser tab is open and the upgrade is done while the user is using the app. In this case, perhaps you want to display a modal message to refresh the page, or automatically refresh to load the new version.

For that, you should store the version number (or git commit hash) somewhere in the SPA scope when the app is first opened, and periodically check the current backend version with a webservice call. If you detect a version change, you’ll display the message (and prevent the user from using its old version).

[Vue.js] why component disappear when i change tab?

in my laravel project there is used Vuejs and Vuex.when page is loaded or refreshed then component is displayed but when i change tab and goto previous tab then component disappear.And when i goto next page and return back everything is fine.

below is component featured.vue

<template>
<div class=”featured_slider slider”>
<h4>featured</h4>
<div class=”featured_slider_item” v-for=”product in getFeaturedProducts”>
<div class=”border_active”></div>
<div class=”product_item discount d-flex flex-column align-items-center
justify-content-center text-center”>
<div class=”product_image d-flex flex-column align-items-center justify-
content-center”>
<img :src=”‘/Uploads/Products/‘+product.id+’/cropped_‘+product.image.name”
:alt=”product.image.name”></div>
<div class=”product_content”>
<div class=”product_price discount”>Rs.{product.price_old}<span>Rs.
{product.price_new}</span></div>
<div class=”product_name”>
<div><a href=”#”>{product.title}</a></div>`
</div>
<div class=”product_extras”>
<div class=”product_color”>
<input type=”radio” checked
name=”product_color”style=”background:#b19c83”>
<input type=”radio” name=”product_color”
style=”background:#000000”>
<input type=”radio” name=”product_color”
style=”background:#999999”>
</div>
<button class=”product_cart_button”>Add to Cart</button>
</div>
</div>
<div class=”product_fav”><i class=”fas fa-heart”></i></div>
<ul class=”product_marks”>
<li class=”product_mark product_discount”>-25%</li>
<li class=”product_mark product_new”>new</li>
</ul>
</div>
</div>
</div>
</template>

<script>
export default {
data(){
return{
products:[]
}
},
computed:{
getFeaturedProducts(){
return this.$store.getters.featuredProducts;
}
},
created() {
return this.$store.dispatch(‘featuredProducts’);
}
}
</script>

below is state.js

export default {
featuredProducts:[],
onSale:[]
}

below is getters.js

export const featuredProducts= state =>{
//console.log(state);
return state.featuredProducts
};

export const onSale= state =>{
//console.log(state);
return state.onSale
};

below is mutations.js

export const featuredProducts=(state,responseData)=>{
state.featuredProducts=responseData;
// console.log(responseData)
};

export const onSale=(state,responseData)=>{
state.onSale=responseData;
// console.log(responseData)
};

below is actions.js

import {sendGet} from “../../../utils/request”;
export const featuredProducts =context=>{
sendGet(‘/product/products’).then(response=>{
context.commit(‘featuredProducts’,response.data.data)
});
};

export const onSale =context=>{
sendGet(‘/product/onsale’).then(response=>{
context.commit(‘onSale’,response.data.data)
});
};

Solution :

Considering general file structure ‘public>js>app.js’, app.js
which include all compiled js, the vue.js dependencies and attach vue.js instance to to
the body of the page, the blade, eg index.blade.php you might have something like ::

<script type=”text/javascript” src=”js/app.js”></script>

In the blade template, change it into something like this, considering same file structure:

<script type=”text/javascript” src=”{url(‘js’)}/app.js”></script>

[Vue.js] How to use multiple Clappr in slider, vue?

there is created a slider consisting of multiple images and videos. I use Swiper and Clappr (video player), but clappr doesn’t work with multiple videos.

I tried to fix it through a cycle (code below), but even so, the script only works for the first video.

vue.js v.3.1, Clappr v.0.3, Swiper v.4.5.

<section class=”content__slider swiper-container”
v-if=”project_data && project_data.length”>

<ul class=”swiper-wrapper”>
<li v-for=”(object, index) in project_data” :key=”index”
class=”content-item swiper-slide”>

<!– it’ll be show, if obj type is images –>
<v-lazy-image v-if=”object.type === ‘images’”
:src=”object.data”
class=”content-img”/>

<!– it’ll be show, if obj type is video –>
<div v-if=”object.type === ‘video’”
class=”content-video”
:id=”‘container_‘ + index”></div>

</li>
</ul>

</section>

import axios from ‘axios’
import Swiper from “swiper/dist/js/swiper.esm.bundle”;
import VLazyImage from “v-lazy-image”;
import Clappr from ‘clappr’

import ‘swiper/dist/css/swiper.min.css’

export default {
name: “Project”,
data: () => ({
project_data: [], // data of project
project_images: [], // arr of images
project_videos: [], // arr of videos
}),
created() {

axios.get(‘/getWorks/‘ + this.$route.params.name)
.then(response => {

let arr = [];

this.project_images = response.data.work_images;
let images = response.data.work_images;

this.project_videos = response.data.work_videos;
let videos = response.data.work_videos;

for (let i = 0; i < images.length; i++) {
arr.push({“type”: “images”, “data”: “/storage/“ + images[i]});
}
for (let i = 0; i < videos.length; i++) {
arr.push({“type”: “video”, “data”: “/storage/“ + videos[i]});
}

this.project_data = arr;

})
.then(() => {

// init slider
new Swiper(‘.content__slider’, {
mousewheel: true,
keyboard: true,
speed: 1200,
navigation: {
nextEl: ‘.content-arrow.swiper-button-next’,
prevEl: ‘.content-arrow.swiper-button-prev’,
},
pagination: {
el: ‘.content-pagination.swiper-pagination’,
type: ‘fraction’,
},
breakpoints: {
959: {
zoom: {
maxRatio: 5,
toggle: true,
containerClass: ‘.content__slider’,
zoomedSlideClass: ‘.content-item’
},
}
}
});

// init clappr (video player)
if ( document.querySelector(‘.content-video’) ) {
for (let i = 0; i < this.project_videos.length; i++) {
new Clappr.Player({
source: ‘/storage/‘ + this.project_videos[i],
parentId: ‘#container_‘ + (this.project_images.length - i),
mute: true,
width: document.querySelector(‘.content-item’).offsetWidth,
height: document.querySelector(‘.content-item’).offsetHeight
});
}
}
});
}
}

It’s works for the first video in array, but not for the following

Solution :

Live and learn, I did not notice my mistake.

parentId: ‘#container_‘ + (this.project_images.length + i)

It was necessary to summarize. Now, it works)

Solution 2:

the problem is:

you are initializing clappr on created hook (not ideal)
you are initializing only the first one due to using `v-if

The created hook is triggered before the component is finished building its DOM, therefore in theory, you would not be able to find any elements via the document.querySelector.

Why does this work tho?

Since you are running this querySelector inside a asynchronous function(the ajax call from axios), this means that the time it takes the server to respond the call to /getWorks/, the browser has been done creating the DOM. This is pure luck and not what you would want to do.

Solution to #1; Change created hook to a mounted hook. Mounted is the hook vue.js uses to tell you that the DOM is build and completed.

The second issue is that you are using v-if to “hide” the other elements. v-if completly removes the element from DOM. This makes the querySelector not being able to find it and initialize it. (Because there is only one, and that is the first element:

so, the script only works for the first video.

Solution to #2 Change v-if to v-show v-show is keeping the element in DOM but hiding it via CSS. Therefore it is accessible via querySelector.

[Vue.js] How to access auth instance in fetch()?

when using nuxt-auth module and when refactoring my code, that is why to access the auth instance within fetch() method I use in pages/index.vue.js component page.

I tried:

console.log(this.$auth)
console.log($auth)

I get undefined.

Note that elsewhere, I access the auth instance without any problem.

Solution :

You can access through vuex: store.state.auth

async fetch ({ store }) {
store.$state.$auth
}

[Vue.js] Is there a way to send a GET request in an API endpoint for xlsx for the vuejs to use?

I’ve already set up an endpoint that returns a specific data based on the DateFilter that I’ve created. And when Using the ?format=xlsx it downloads an xlsx file with the list of specific data based on the DateFilter that was requested. I’m also done on the search function in the frontend by passing the url in the searchCarriers, the only thing missing now is to have a downloadable xlsx in the frontend. How can I do this?

This is my DateFilter

class CarrierFilter(django_filters.FilterSet):
date_app_rec__gte = DateFilter(field_name=’date_app_rec’, lookup_expr=’gte’)
date_app_rec__lte = DateFilter(field_name=’date_app_rec’, lookup_expr=’lte’)
date_sample_rec__gte = DateFilter(field_name=’date_sample_rec’, lookup_expr=’gte’)
date_sample_rec__lte = DateFilter(field_name=’date_sample_rec’, lookup_expr=’lte’)
date_of_qca__gte = DateFilter(field_name=’date_of_qca’, lookup_expr=’gte’)
date_of_qca__lte = DateFilter(field_name=’date_of_qca’, lookup_expr=’lte’)
date_created__gte = DateFilter(field_name=’date_created’, lookup_expr=’gte’)
date_created__lte = DateFilter(field_name=’date_created’, lookup_expr=’lte’)
patient_name = CharFilter(field_name=’patient_name’, lookup_expr=’icontains’)

class Meta:
model = Carrier
fields = (‘date_app_rec__gte’, ‘date_app_rec__lte’,
‘date_sample_rec__gte’, ‘date_sample_rec__lte’,
‘date_of_qca__gte’, ‘date_of_qca__lte’,
‘date_created__gte’, ‘date_created__lte’,
‘patient_name’,)

This is my ModelViewSet

class CarrierViewSet(XLSXFileMixin, ModelViewSet):
queryset = Carrier.objects.all()
serializer_class = CarrierSerializer
permission_classes = (IsAuthenticated,)
parser_classes = (MultiPartParser,) # for uploading of attachments
filename = ‘carrier-reports.xlsx’
filter_class = (CarrierFilter) # filtering From date and To date
filterset_fields = (‘patient_name’, ‘promo_code’)
search_fields = (‘patient_name’, ‘promo_code’, ‘insurance_verified_tsg_verification’)

This returns all the specific dates in the table in the frontend

searchCarriers: function () {
// Search function
api_url = `/api/v1/carrier/?date_app_rec__gte=${this.carrier_from_date_app_rec}&date_app_rec__lte=${this.carrier_to_date_app_rec}&date_sample_rec__gte=${this.carrier_from_date_sample_rec}&date_sample_rec__lte=${this.carrier_to_date_sample_rec}&date_of_qca__gte=${this.carrier_from_date_of_qca}&date_of_qca__lte=${this.carrier_to_date_of_qca}&date_created__gte=${this.carrier_from_date_created}&date_created__lte=${this.carrier_to_date_created}&patient_name=${this.carrier_search_patient_name}`
this.searching = true;
this.$http.get(api_url)
.then((response) => {
this.carriers = response.data;
this.searching = false;
})
.catch((err) => {
this.searching = false;
console.log(err);
})
},

Solution :

You can request URL as you do by using GET
but you have to take care of what are you doing

Front-end Side:
Using download attribute

this.$http.get(api_url)
.then((response) => {
let a= document.createElement(‘A’)
a.href= response.data
a.download = true
document.body.appendChild(a)
a.click()
}

if you don’t want to appear you can manage by CSS display:none or opacity:0

Back-end Side:

you have to add to the data or the link you provide as response Header Content-Disposition

Content-Disposition: ‘attachment’ // for example

[Vue.js] Promise skip all fulfill and reject reactions but execute .finally

there is function called request:

function request (endpoint) {
return axios.request(endpoint).then(api.onSuccess).catch(api.onError)
}

api.onSuccess:

onSuccess (response) {
let breakChain = false
… some logic goes here …
return breakChain ? (new Promise(() => {})) : response
}

api.onError:

onError (error) {
let breakChain = false
… some logic goes here …
if (breakChain) {
return new Promise(() => {})
} else {
throw error
}
}

api holds a lot of functions that represent different API calls based on provided endpoints data and return request(endpoint).

Currenly there is code, as you can see, that return Promise with empty executor that is always in pending state to stop the chain of subsequent .then(…) and .catch(…) handlers from execution as they just infinitely wait for that Promise to settle. This is done to handle certain API responses that have common response handling (like responses with code >= 500).
The problem is that now I need a call to .finally() (like in vue.js cookbook - https://vuejs.org/v2/cookbook/using-axios-to-consume-apis.html#Dealing-with-Errors) to restore some component’s state nevertheless of whether there is an error or not, but this approach of pending Promise is an obstacle.

The question is: is it possible to skip all subsequent .then(…) and .catch(…) calls within one of such handlers to go directly to .finally()?

Update. I haven’t mentioned the important bit - api.onSuccess and api.onError are basic handlers. In another application components there are additional handlers appended to the end of that basic chain presented in request function. Usual chain of some API call has a following resulting form:

return axios.request(endpoint).then(api.onSuccess).catch(api.onError).then((response) => {…}).catch(() => {…}).finally(() => {…})

(sometimes there is no .finally() or .catch(…) block)

Solution :

Is it possible to skip all subsequent .then(…) and .catch(…) calls within one of such handlers to go directly to .finally()?

No.

Currenly I stop the chain by just infinitely waiting - yet this approach of pending Promise is an obstacle.

Indeed, don’t do that. You can skip then handlers by using rejections (exceptions) for flow control, but the more appropriate way is to handle this by nesting the part of the chain to be skipped inside an if statement.

This is done to handle certain API responses that have common response handling (like responses with code >= 500)

For that, you should use something like

return axios.request(endpoint).then(response => {

}).catch(error => {
if (api.handleCommonError(error)) return; // returns false if it couldn’t handle the error

}).finally(() => {

});

Yes, you cannot hide this kind of error handling inside an api.request function.

Solution 2:

You can use async and await. All modern browsers support them, and the bundler can make them compatible with older browsers.

For example:

async function request (endpoint) {
try {
const response = await axios.request(endpoint);
return api.onSuccess(response);
} catch (err) {
api.onError(err);
} finally {
// Always executed, even if no error was thrown
}
}

You can also do it more traditionally:

function request (endpoint) {
return axios.request(endpoint).then(api.onSuccess, api.onError).then(() => {
// Code is always executed after error / success
}
}

[Vue.js] Element UI with VueJS Autocomplete Avoid Mutation A Props (Vue Warn)

there is a big problem with VueJS and Element UI https://element.eleme.io/#/en-US/component/input#autocomplete-attributes
I use the AutoComplete Component, and that I click on the input (onFocus Event), my suggestions re appear

<el-autocomplete
id=”inputID”
name=”inputName”
class=”inputClass”
v-model=”inputModel”
:fetch-suggestions=”querySearchInput”
placeholder= “Select an Input”
ref=”inputReference”
value-key=”id”
v-loading=”inputLoader”
:value=”inputValue”
@select=”onChangeInput”
@focus=”onFocusInput”
@clear=”onClearInput”
clearable
\>
<!– Slot : Override Component Suggestions –>
<template slot-scope=”{item}” v-if=”item.id”>
{ item.id } - { item.name }
</template>
</el-autocomplete>

on my onFocus or onClear i used :

this.inputModel = “”;
this.inputValue = “”

But it does not reset my suggestions.. :/
The only way for me is to use :

this.$refs.inputReference.value = “”;

But it’s not a best pratice there is a message : “ vue.esm.js?efeb:591 [vue.js warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop’s value. Prop being mutated: “value” “

I use a :value and a v-model on my component because i stock an ID but i display a label with i18n, isn’t important

VERY THANKS YOU

I think it’s because the AutoComplete Component includes a InputComponent, and i’m not a pro with the cascading prop on VueJS..

Thanks.

Solution :

Just do like it says. Do not mutate props. If you need to change some date from props, save it to local component data and modify it

props: {
foo: {
type: number,
requred: true
}
},

data () {
return {
localFoo: this.foo
}
}

[Vue.js] Using mutationobservers to detect changes in the results of a fetch request

I’m working on a narrow cast that displays an amount of tickets (an integer with the total added up to eachother) from a 3rd party API. to display a notification when this amount increases. I’ve read about mutationobservers, and that they are good for doing similar tasks like when something gets added or deleted.

The app has a vue.js frontend, and a Laravel backend which does the requesting/authenticating. The index blade loads in a vue.js component which contains the other components (and distributes the data from the API to child components).

I’m not quite sure wether mutationobservers are good for this specific job, though. Googling really didn’t give me great alternatives.

In conclusion, to know if mutationobservers are the right tools for this task and what property would work. Better suited alternatives are also welcome.

Solution :

Using vue, you can use a watcher function to watch for changes in a particular variable (amount). Mutation Observers only watches for dom updates, it won’t give you what you want

[Vue.js] How to call a vue.js function on page load

there is a function that helps filter data. when using v-on:change when a user changes the selection but I also need the function to be called even before the user selects the data. there is done the same with AngularJS previously using ng-init but I understand that there is no such a directive in vue.js

This is my function:

getUnits: function () {
var input = {block: this.block, floor: this.floor, unit_type: this.unit_type, status: this.status};

this.$http.post(‘/admin/units’, input).then(function (response) {
console.log(response.data);
this.units = response.data;
}, function (response) {
console.log(response)
});
}

In the blade file I use blade forms to perform the filters:

<div class=”large-2 columns”>
{!! Form::select(‘floor’, $floors,null, [‘class’=>’form-control’, ‘placeholder’=>’All Floors’, ‘v-model’=>’floor’, ‘v-on:change’=>’getUnits()’ ]) !!}
</div>
<div class=”large-3 columns”>
{!! Form::select(‘unit_type’, $unit_types,null, [‘class’=>’form-control’, ‘placeholder’=>’All Unit Types’, ‘v-model’=>’unit_type’, ‘v-on:change’=>’getUnits()’ ]) !!}
</div>

This works fine when I select a specific item. Then if I click on all lets say all floors, it works. What I need is when the page is loaded, it calls the getUnits method which will perform the $http.post with empty input. In the backend there is handled the request in a way that if the input is empty it will give all the data.

How can I do this in vuejs2?

My Code: http://jsfiddle.net/q83bnLrx

Solution :

You can call this function in beforeMount section of a vue.js component: like following:

….
methods:{
getUnits: function() {…}
},
beforeMount(){
this.getUnits()
},
……

Working fiddle: https://jsfiddle.net/q83bnLrx/1/

There are different lifecycle hooks vue.js provide:

there is listed few are :

beforeCreate: Called synchronously after the instance has just been initialized, before data observation and event/watcher setup.
created: Called synchronously after the instance is created. At this stage, the instance has finished processing the options which means the following have been set up: data observation, computed properties, methods, watch/event callbacks. However, the mounting phase has not been started, and the $el property will not be available yet.
beforeMount: Called right before the mounting begins: the render function is about to be called for the first time.
mounted: Called after the instance has just been mounted where el is replaced by the newly created vm.$el.
beforeUpdate: Called when the data changes, before the virtual DOM is re-rendered and patched.
updated: Called after a data change causes the virtual DOM to be re-rendered and patched.

You can have a look at complete list here.

You can choose which hook is most suitable to you and hook it to call you function like the sample code provided above.

Solution 2:

You need to do something like this (If you want to call the method on page load):

new Vue({
// …
methods:{
getUnits: function() {…}
},
created: function(){
this.getUnits()
}
});

Solution 3:

you can also do this using mounted

https://vuejs.org/v2/guide/migration.html#ready-replaced

….
methods:{
getUnits: function() {…}
},
mounted: function(){
this.$nextTick(this.getUnits)
}
….