How to abort method in vue - javascript

I am using vue #keyup on input, this uses method with axios call:
<template>
<div>
<input type="text" placeholder="Where are you from?" v-model="from" #keyup="getPlace">
<ul>
<li v-for="place in places">{{ place.name }}<li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
places: [],
from: ''
}
},
methods() {
if(this.from.length <= 3) { this.places = []; return; }
getPlace() {
axios.get('/places?name='+this.from).then((res)=>{
this.places = [];
for(var i = 0; i<res.data.length; i++) {
this.places.push(res.data[i]);
}
}).catch((err)=>{console.log(err)});
}
}
};
</script>
Now this works but it has a big problem, each call it updates array of places but it is late, so the method is called and array has been returned to [] but after the response is back it is populating the array for each keyup (if you type fast)... I am switching from jquery front to this and I never ever had a problem with this :O

This doesn't answer the "how to abort method", but you could use a different approach for your example: Fetching all places at the beginning (mounted()) and filter them based on the input in the frontend by using a computed property.
var app = new Vue({
el: '#app',
data() {
return {
places: [],
from: ''
}
},
mounted() {
this.getPlaces();
},
computed: {
placesList() {
let result = []
let places = this.places
let from = this.from
if (from !== '') {
result = this.places.filter(element => {
return element.name.toLowerCase().includes(from.toLowerCase())
})
} else {
result = places
}
return result
}
},
methods: {
getPlaces() {
// axios call..
this.places = [{
id: 1,
name: "Germany"
}, {
id: 2,
name: "USA"
}, {
id: 3,
name: "Spain"
}]
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.17/dist/vue.js"></script>
<div id="app">
<input type="text" placeholder="Where are you from?" v-model="from">
<br /> input text: {{ from }}
<hr>
<ul>
<li v-for="place in placesList" :key="place.id">
{{ place.name }}
</li>
</ul>
</div>

Related

How to get data in real time in vuejs

It is my first project in vue. I am getting the cart-data from the server. i want to change quantity from the vue. When i click change quantity i.e up arrow and down arrow, change is reflected in the server database. but in UI i have to reload the page to see change which i do not want that.
i want to see the change in without reloading when button is click. and i want to run TotalCartPrice method without clicking any button. I mean when i open cart it should be automatically run. what is wrong?
cart.vue
<template>
<CartItem v-for="cart in carts" :key="cart.id" :carts="cart" />
</template>
<script>
import CartItem from "../components/cart/cartItem";
export default {
name: "CartPage",
components: {
CartItem
},
computed: {
...mapGetters(["carts"])
},
created() {},
methods: {
TotalCartPrice() {
var total = 0;
for (var i = 0; i < this.carts.length; i++) {
total += this.carts[i].product.price * this.carts[i].quantity;
}
return total;
}
}
};
CartItem.vue
<template>
<div>
<h5>${{ carts.product.price }}</h5>
<div class="product_count">
<input
disabled
name="qty"
maxlength="12"
:value="carts.quantity"
class="input-text qty"
/>
<button
#click="addProduct()"
class="increase items-count"
type="button"
>
<i class="lnr lnr-chevron-up"></i>
</button>
<button
#click="removeProduct()"
class="reduced items-count"
type="button"
>
<i class="lnr lnr-chevron-down"></i>
</button>
</div>
</div>
</template>
<script>
export default {
name: "cartItem",
props: {
carts: {
required: true,
type: Object
}
},
data() {
return {
cartDetail: {
product: this.carts.product.id,
quantity: null,
customer: null,
checkout: false
}
};
},
computed: {
...mapGetters(["authUser"])
},
methods: {
...mapActions(["addTocart"]),
addProduct() {
this.cartDetail.quantity = 1;
this.cartDetail.customer = this.authUser.id;
this.addTocart(this.cartDetail);
},
removeProduct() {
this.cartDetail.quantity = -1;
this.cartDetail.customer = this.authUser.id;
this.addTocart(this.cartDetail)
}
}
};
</script>
Cart.js
const state = {
carts: []
};
const getters = {
carts: state => state.carts
};
const actions = {
async addTocart({ commit }, data) {
const JsonData = JSON.parse(JSON.stringify(data));
const response = await axios.post("/api/v1/cart/view-set/", JsonData);
return response;
},
async cart({ commit }, data) {
if (data !== "null") {
const response = await axios.get(`/api/v1/cart/cartdetial/${data}`);
commit("setCarts", response.data);
return response;
}
}
};
const mutations = {
setCarts: (state, carts) => {
state.carts = carts;
}
};
export default {
state,
getters,
actions,
mutations
};
TotalCartPrice should be a computed property:
TotalCartPrice: function() {
var total = 0;
for (var i = 0; i < this.carts.length; i++) {
total += this.carts[i].product.price * this.carts[i].quantity;
}
return total;
}
From the docs on the difference between computed and methods:
...computed properties are cached based on their reactive dependencies. A computed property will only re-evaluate when some of its reactive dependencies have changed. This means as long as message has not changed, multiple access to the reversedMessage computed property will immediately return the previously computed result without having to run the function again.
This way, your cart price will update whenever this.carts is updated.

How do I render a child component within an iframe in Vue?

So I want to show the user a preview of what an email will look like before it's sent out. To avoid styles from leaking from the parent page into the preview, I've decided to use an iframe. I want the preview to update in real time as the user enters form details.
How would I render a component within an iframe so that its props update automatically when the parent form is updated? This is the code I have so far:
this is the html:
<template>
<div id="confirmation">
<h2>Give a gift</h2>
<form #submit.prevent="checkout()">
<div class="date-section">
<label class="wide">Send</label>
<input type="radio" name="sendLater" v-model="sendLater" required :value="false">
<span>Now</span>
<input type="radio" name="sendLater" v-model="sendLater" required :value="true">
<span style="margin-right: 5px;">Later: </span>
<date-picker :disabled="!sendLater" v-model="date" lang="en" />
</div>
<div>
<label>Recipient Email</label>
<input type="email" class="custom-text" v-model="form.email" required>
</div>
<div>
<label>Recipient Name</label>
<input type="text" class="custom-text" v-model="form.name" required>
</div>
<div>
<label>Add a personal message</label>
<textarea v-model="form.message" />
</div>
<p class="error" v-if="error">Please enter a valid date.</p>
<div class="button-row">
<button class="trumpet-button" type="submit">Next</button>
<button class="trumpet-button gray ml10" type="button" #click="cancel()">Cancel</button>
</div>
</form>
<iframe id="preview-frame">
<preview-component :form="form" :sender-email="senderEmail" :term="term" />
</iframe>
</div>
</template>
here is the js (note: PreviewComponent is the actual preview that will be rendered in the iframe):
export default {
name: 'ConfirmationComponent',
components: {
DatePicker,
PreviewComponent
},
props: {
term: {
required: true,
type: Object
}
},
data() {
return {
form: {
name: null,
email: null,
message: null,
date: null
},
date: null,
sendLater: false,
error: false
}
},
computed: {
senderEmail() {
// utils comes from a separate file called utils.js
return utils.user.email || ''
}
},
watch: {
'form.name'(val) {
this.renderIframe()
},
'form.email'(val) {
this.renderIframe()
}
},
methods: {
renderIframe() {
if (this.form.name != null && this.form.email != null) {
console.log('rendering iframe')
// not sure what to do here......
}
}
}
}
I've tried all sorts of things but what seems to be the hardest is setting the props of the preview-component properly. Any help you all can give would be appreciated.
So as posted in one of the comments, Vuex works perfectly for this.
I also ended up creating a custom "IFrame" component that renders whatever you have inside its slot in an iframe.
Here is my Vuex store:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export const store = new Vuex.Store({
state: {
form: {
name: null,
email: null,
message: null
},
senderEmail: null,
term: null,
styles: null
},
mutations: {
updateForm(state, form) {
state.form = form
},
updateEmail(state, email) {
state.senderEmail = email
},
updateTerm(state, term) {
state.term = term
},
stylesChange(state, styles) {
state.styles = styles
}
}
})
my IFrame component:
import Vue from 'vue'
import { store } from '../../store'
export default {
name: 'IFrame',
data() {
return {
iApp: null,
}
},
computed: {
styles() {
return this.$store.state.styles
}
},
render(h) {
return h('iframe', {
on: {
load: this.renderChildren
}
})
},
watch: {
styles(val) {
const head = this.$el.contentDocument.head
$(head).html(val)
}
},
beforeUpdate() {
this.iApp.children = Object.freeze(this.$slots.default)
},
methods: {
renderChildren() {
const children = this.$slots.default
const body = this.$el.contentDocument.body
const el = document.createElement('div') // we will mount or nested app to this element
body.appendChild(el)
const iApp = new Vue({
name: 'iApp',
store,
data() {
return {
children: Object.freeze(children)
}
},
render(h) {
return h('div', this.children)
}
})
iApp.$mount(el)
this.iApp = iApp
}
}
}
finally here is how data is passed to the PreviewComponent from the ConfirmationComponent:
export default {
name: 'ConfirmationComponent',
mounted() {
this.$store.commit('updateEmail', this.senderEmail)
this.$store.commit('updateTerm', this.term)
},
watch: {
'form.name'(val) {
this.updateIframe()
},
'form.email'(val) {
this.updateIframe()
}
},
methods: {
updateIframe() {
this.$store.commit('updateForm', this.form)
}
}
}
then lastly the actual PreviewComponent:
import styles from '../../../templates/styles'
export default {
name: 'PreviewComponent',
mounted() {
this.$store.commit('stylesChange', styles)
},
computed: {
redemption_url() {
return `${window.config.stitcher_website}/gift?code=`
},
custom_message() {
if (this.form.message) {
let div = document.createElement('div')
div.innerHTML = this.form.message
let text = div.textContent || div.innerText || ''
return text.replace(/(?:\r\n|\r|\n)/g, '<br>')
}
return null
},
form() {
return this.$store.state.form
},
term() {
return this.$store.state.term
},
senderEmail() {
return this.$store.state.senderEmail
}
}
}
hopefully this will help somebody.

click event on div and filter vuex data --vue.js

I am stuck at this very point: exporting filter function and using it in vuex store. No problem'till here. Now am trying to put #click event on divs. And when I click, for example. Audi the filter needs to show just "audi" And if I click "audi" again then it needs remove it from the filter.
Here is the sandbox: https://codesandbox.io/s/filtering-bzphi
filter.js
export const carFilter = car => allcars => {
if (car.length > 0) {
if (allcars.name.includes(car)) {
return true;
} else {
return false;
}
} else {
return true;
}
};
Store
export const store = new Vuex.Store({
state: {
cars: [
{ name: "AUDI" },
{ name: "BMW" },
{ name: "MERCEDES" },
{ name: "HONDA" },
{ name: "TOYOTA" }
],
carBrand: []
},
mutations: {
updateCarsFilter(state, carBrand) {
state.carBrand = carBrand;
}
},
getters: {
filteredCars: state => {
return state.cars.filter(carFilter(state.carBrand));
}
}
});
and App.js
<template>
<div id="app">
<div class="boxes" :key="index" v-for="(item, index) in cars">{{item.name}}</div>
<List/>
</div>
</template>
<script>
import List from "./List.vue";
export default {
name: "App",
components: {
List
},
computed: {
selectBrand: {
set(val) {
this.$store.commit("updateCarsFilter", val);
},
get() {
return this.$store.state.carBrand;
}
},
cars() {
return this.$store.getters.filteredCars;
}
}
};
</script>
I also created a sandbox for this. You can check it for better understanding. https://codesandbox.io/s/filtering-bzphi
In the store.js
changed the carBrand default to ''
added Mutation clearFilter
added Getter isActiveFilter
update
remove carBrand from state
replaced by selectedCars that is an array
removed mutation about carBrand
added mutation addCarSelection removeCarSelection
filteredCars return selectedCars array if contains cars, otherwise cars state
added isSelectedCar to check if a car is in the selection
carFilter function from filter.js is no longer needed.
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
cars: [
{ name: "AUDI" },
{ name: "BMW" },
{ name: "MERCEDES" },
{ name: "HONDA" },
{ name: "TOYOTA" }
],
selectedCars: []
},
mutations: {
addCarSelection(state, car) {
state.selectedCars.push(car);
},
removeCarSelection(state, car) {
state.selectedCars = state.selectedCars.filter(r => r.name !== car.name);
}
},
getters: {
filteredCars: state => {
if (state.selectedCars.length !== 0) {
// There's selected cars, return filtered
return state.selectedCars;
} else {
return state.cars;
}
},
isSelectedCar: state => car => {
return state.selectedCars.some(r => r.name === car.name);
}
}
});
In the App.vue
added method filterCars (moved from computed property searchText)
added method clearFilter
update
removed filterCars and 'clearFilter' method and mapped new mutation and getters from store
methods: {
addCarSelection(car) {
this.$store.commit("addCarSelection", car);
},
removeCarSelection(car) {
this.$store.commit("removeCarSelection", car);
},
isSelectedCar(car) {
return this.$store.getters.isSelectedCar(car)
},
}
added isFilterActive() computed property
update
removed isFilterActive() and searchText from computed property
computed: {
cars() {
return this.$store.getters.filteredCars;
},
},
update
Changed the Template code to manage #click event to add car or remove car from selection
boxes always show cars available, if isSelectedCar toggle between add or remove function.
List show selected cars if presents otherwise the full car catalog.
<template>
<div id="app">
<div class="boxes" :key="index" v-for="(item, index) in cars">
<div
v-if="!isSelectedCar(item)"
style="cursor:pointer"
#click="addCarSelection(item)"
>{{item.name}}</div>
<div v-else style="cursor:pointer;" #click="removeCarSelection(item)">
{{item.name}}
<small>[x]</small>
</div>
</div>
<List/>
</div>
</template>
Updated version is available in this sandbox
https://codesandbox.io/s/filtering-3ej7d

Vuejs v-model overwritting array

I am using Vuejs 2 with laravel. Currently i was working with select boxes for a permissions module and it is a box complex structure. The issue i am having is when i try to bind my nested array item in v-model it acts as string. everytime i check a box it overwrites the variable.
workspace.selectedOperations is the model that is overwriting.
This is the html for it :
<b-tab v-for="workspace in addedWorkspaces" :key="workspace.id" :title="workspace.title" active>
<div class="roles-permissions">
<label>Permissions</label>
<div class="permissions-path">
<ul class="pl-0">
<li v-for="entity in workspace.entities">
<b-form-checkbox>{{entity.title}}</b-form-checkbox>
<ul>
<li v-for="operation in entity.operations">{{workspace.selectedOperations}}
<b-form-checkbox v-model="workspace.selectedOperations" :value="operation.id">{{operation.title}}</b-form-checkbox>
</li>
</ul>
</li>
</ul>
</div>
</div>
</b-tab>
This is the script :
<script>
import Multiselect from 'vue-multiselect'
export default {
props : ['showModalProp'],
data () {
return {
title : '',
value: [],
entities : [],
addedWorkspaces : [],
selectedWorkspaces : '',
}
},
methods: {
getOperationsList(){
this.$http.get('entity').then(response=>{
response = response.body.response;
this.entities = response.data;
});
},
showModal() {
this.$refs.myModalRef.show()
},
hideModal() {
this.$refs.myModalRef.hide()
},
onHidden(){
this.$emit('HideModalValue');
},
addWorkspaces(){
this.addedWorkspaces = this.selectedWorkspaces;
this.selectedWorkspaces = [];
for (var i = this.addedWorkspaces.length - 1; i >= 0; i--) {
this.addedWorkspaces[i].entities =
JSON.parse(JSON.stringify(this.entities));
this.addedWorkspaces[i].selectedOperations = [];
}
}
},
mounted(){
this.getOperationsList();
},
components: {
Multiselect
},
watch:{
showModalProp(value){
if(value){
this.showModal();
}
if(!value){
this.hideModal();
}
}
},
computed :{
options(){
return this.$store.getters.getWorkspaces;
}
}
}
</script>
if you want v-model of b-form-checkbox to be an array,you should wrap your b-form-checkbox by b-form-checkbox-group and set v-model on it
see https://bootstrap-vue.js.org/docs/components/form-checkbox

VueJs watching deep changes in object

I have this 3 components in VueJS. The problem i want to solve is: When i click at vehicle component, it needs to be selected (selected = true) and other vehicles unselected.
What i need to do for two-way data binding? Because i'm changing this selected property in VehiclesList.vue component and it also need to be changed in Monit.vue (which is a parent) and 'Vehicle.vue' need to watch this property for change class.
Also problem is with updating vehicles. In Monit.vue i do not update full object like this.vehicles = response.vehicles, but i do each by each one, and changing only monit property.
Maybe easier would be use a store for this. But i want to do this in components.
EDITED:Data sctructure
{
"m":[
{
"id":"v19",
"regno":"ATECH DOBLO",
"dt":"2017-10-09 13:19:01",
"lon":17.96442604,
"lat":50.66988373,
"v":0,
"th":0,
"r":0,
"g":28,
"s":"3",
"pow":1
},
{
"id":"v20",
"regno":"ATECH DUCATO_2",
"dt":"2017-10-10 01:00:03",
"lon":17.96442604,
"lat":50.6698494,
"v":0,
"th":0,
"r":0,
"g":20,
"s":"3"
},
]
}
Monit.vue
<template>
<div class="module-container">
<div class="module-container-widgets">
<vehicles-list :vehicles="vehicles"></vehicles-list>
</div>
</div>
</template>
<script>
import VehiclesList from '#/components/modules/monit/VehiclesList.vue';
export default {
name: "Monit",
data (){
return {
vehicles: null
}
},
components: {
VehiclesList
},
methods: {
getMonitData(opt){
let self = this;
if (this.getMonitDataTimer) clearTimeout(this.getMonitDataTimer);
this.axios({
url:'/monit',
})
.then(res => {
let data = res.data;
console.log(data);
if (!data.err){
self.updateVehicles(data.m);
}
self.getMonitDataTimer = setTimeout(()=>{
self.getMonitData();
}, self.getMonitDataDelay);
})
.catch(error => {
})
},
updateVehicles(data){
let self = this;
if (!this.vehicles){
this.vehicles = {};
data.forEach((v,id) => {
self.vehicles[v.id] = {
monit: v,
no: Object.keys(self.vehicles).length + 1
}
});
} else {
data.forEach((v,id) => {
if (self.vehicles[v.id]) {
self.vehicles[v.id].monit = v;
} else {
self.vehicles[v.id] = {
monit: v,
no: Object.keys(self.vehicles).length + 1
}
}
});
}
},
},
mounted: function(){
this.getMonitData();
}
};
</script>
VehiclesList.vue
<template>
<div class="vehicles-list" :class="{'vehicles-list--short': isShort}">
<ul>
<vehicle
v-for="v in vehicles"
:key="v.id"
:data="v"
#click.native="select(v)"
></vehicle>
</ul>
</div>
</template>
<script>
import Vehicle from '#/components/modules/monit/VehiclesListItem.vue';
export default {
data: function(){
return {
isShort: true
}
},
props:{
vehicles: {}
},
methods:{
select(vehicle){
let id = vehicle.monit.id;
console.log("Select vehicle: " + id);
_.forEach((v, id) => {
v.selected = false;
});
this.vehicles[id].selected = true;
}
},
components:{
Vehicle
}
}
</script>
Vehicle.vue
<template>
<li class="vehicle" :id="data.id" :class="classes">
<div class="vehicle-info">
<div class="vehicle-info--regno font-weight-bold"><span class="vehicle-info--no">{{data.no}}.</span> {{ data.monit.regno }}</div>
</div>
<div class="vehicle-stats">
<div v-if="data.monit.v !== 'undefined'" class="vehicle-stat--speed" data-name="speed"><i class="mdi mdi-speedometer"></i>{{ data.monit.v }} km/h</div>
</div>
</li>
</template>
<script>
export default {
props:{
data: Object
},
computed:{
classes (){
return {
'vehicle--selected': this.data.selected
}
}
}
}
</script>
Two-way component data binding was deprecated in VueJS 2.0 for a more event-driven model: https://v2.vuejs.org/v2/guide/components.html#One-Way-Data-Flow
This means, that changes made in the parent are still propagated to the child component (one-way). Changes you make inside the child component need to be explicitly send back to the parent via custom events: https://v2.vuejs.org/v2/guide/components.html#Custom-Events or in 2.3.0+ the sync keyword: https://v2.vuejs.org/v2/guide/components.html#sync-Modifier
EDIT Alternative (maybe better) approach:
Monit.vue:
<template>
<div class="module-container">
<div class="module-container-widgets">
<vehicles-list :vehicles="vehicles" v-on:vehicleSelected="onVehicleSelected"></vehicles-list>
</div>
</div>
</template>
<script>
import VehiclesList from '#/components/modules/monit/VehiclesList.vue';
export default {
name: "Monit",
data (){
return {
vehicles: null
}
},
components: {
VehiclesList
},
methods: {
onVehicleSelected: function (id) {
_.forEach((v, id) => {
v.selected = false;
});
this.vehicles[id].selected = true;
}
...other methods
},
mounted: function(){
this.getMonitData();
}
};
</script>
VehicleList.vue:
methods:{
select(vehicle){
this.$emit('vehicleSelected', vehicle.monit.id)
}
},
Original post:
For your example this would probably mean that you need to emit changes inside the select method and you need to use some sort of mutable object inside the VehicleList.vue:
export default {
data: function(){
return {
isShort: true,
mutableVehicles: {}
}
},
props:{
vehicles: {}
},
methods:{
select(vehicle){
let id = vehicle.monit.id;
console.log("Select vehicle: " + id);
_.forEach((v, id) => {
v.selected = false;
});
this.mutableVehicles[id].selected = true;
this.$emit('update:vehicles', this.mutableVehicles);
},
vehilcesLoaded () {
// Call this function from the parent once the data was loaded from the api.
// This ensures that we don't overwrite the child data with data from the parent when something changes.
// But still have the up-to-date data from the api
this.mutableVehilces = this.vehicles
}
},
components:{
Vehicle
}
}
Monit.vue
<template>
<div class="module-container">
<div class="module-container-widgets">
<vehicles-list :vehicles.sync="vehicles"></vehicles-list>
</div>
</div>
</template>
<script>
You still should maybe think more about responsibilities. Shouldn't the VehicleList.vue component be responsible for loading and managing the vehicles? This probably would make thinks a bit easier.
EDIT 2:
Try to $set the inner object and see if this helps:
self.$set(self.vehicles, v.id, {
monit: v,
no: Object.keys(self.vehicles).length + 1,
selected: false
});

Categories