is it possible to access variable in watch() function vue - vue.js

I want to access variable asd in my watch() function and clear asd interval I tried code below but it's not working timer goes below 0 so any possible solutions?
methods:{
testing(){
this.sTimer--;
if(this.sTimer == 0){
clearInterval(this.asd)
}
}
},
watch(){
var asd = setInterval(() => this.testing(), 1000);
}

Your watcher is not watching any thing! You need to provide an data item for which it watches for it's changes
watch: {
item: function (newItem, oldItem) {
console.log(oldItem + " changed to: " + newItem);
}
},
Also, you might want to add your asd variable to data section.
data() {
return{
asd = null;
}
},
methods: {
testing(){
this.sTimer--;
if(this.sTimer == 0){
clearInterval(this.asd)
}
}
},
watch() {
item: function (newItem, oldItem) {
this.asd = setInterval(() => this.testing(), 1000);
}
}

Related

Countdown variable (HH:mm:ss)

I parse a date YYYY-mm-dd and calculate the difference till midnight. The result will be always under 24h, for example 10:01:10 - HH:mm:ss till it expires. I wonder how I could achieve a countdown functionality with the given example.
<template>
<Label :text="date.expires | readableTime"></Label>
</template>
filters: {
readableTime(value) {
var now = moment(new Date());
var end = moment(value);
var diff = moment.duration(end.diff(now));
try {
return moment.utc(diff.as("milliseconds")).format("HH:mm:ss");
} catch (e) {
return "00:00:00";
}
}
}
You must use use timer and reactive data property. I recommend you to safe diff to components data, start timer on component mount and clear it beforeDestroy
data() {
return {
diff: this.calculareDiff()
}
}
methods: {
calculareDiff() {
const now = moment(new Date());
const end = moment(this.date.expires);
this.diff = moment.duration(end.diff(now));
}
},
mounted() {
this.timer = setInterval(() => this.calculareDiff(), 1000)
},
beforeDestroy() {
clearInterval(this.timer)
}

Try to call the vuex getter in watch

I'm trying to call a Vuex getter in the component watch.
But it tells me that it is undefined what is not.
So i try to return the getter in the computed object but still doesn t work.
name: "FreeTalk",
computed: {
...mapGetters(['getCharacter','getResultStatus', 'getFreeTalkText', 'getResult', 'freeTalkResult', 'getFreeTalkNoNative', 'getFreeTalkMedium','getFreeTalkNative']),
progressStatus() {
return this.getResult.progress
},
getStatus() {
return this.getResultStatus
}
},
watch: {
progressStatus: (val) => {
if (val == 100) {
this.status = this.getStatus()
if (this.getStatus === 0) {
this.outputText = this.getFreeTalkNoNative.result;
} else if (this.getStatus === 1) {
this.outputText = this.getFreeTalkMedium;
} else if (this.getStatus === 2) {
this.outputText = this.getFreeTalkNative;
}
}
}
},
data() {
return {
outputText: '',
ready: false,
isRecordDone: false,
status: -1
}
}
}

Wait until API fully loads before running next function -- async/await -- will this work?

I am a beginner with Javascript with a bit of knowledge of VueJs. I have an array called tickets. I also have a data api returning two different data objects (tickets and user profiles).
The tickets have user ids and the user profiles has the ids with names.
I needed to create a method that looks at both of that data, loops through it, and assigns the full name of the user to the view.
I was having an issue where my tickets object were not finished loading and it was sometimes causing an error like firstname is undefined. So, i thought I'd try and write an async/await approach to wait until the tickets have fully loaded.
Although my code works, it just doesn't "feel right" and I am not sure how reliable it will be once the application gets larger.
Can I get another set of eyes as to confirmation that my current approach is OK? Thanks!
data() {
return {
isBusy: true,
tickets: [],
userProfiles: [],
}
},
created() {
this.getUserProfiles()
this.getTickets()
},
methods: {
getUserProfiles: function() {
ApiService.getUserProfiles().then(response => {
this.userProfiles = response.data
})
},
getTickets() {
ApiService.getTickets().then(response => {
this.tickets = response.data
this.assignNames(this.tickets)
this.isBusy = false
})
},
// lets wait until the issues are loaded before showing names;
async assignNames() {
let tickets = await this.tickets
var i
for (i = 0; i < this.tickets.length; i++) {
if (tickets[i].assigned_to !== null) {
const result = this.userProfiles.filter(profile => {
return profile.uid == tickets[i].assigned_to
})
tickets[i].assigned_to = result[0].firstname + ' ' + result[0].lastname
}
}
}
}
}
</script>
There are several ways you could do this. Here is the one I prefer without async/await:
created() {
this.load();
},
methods: {
getUserProfiles: function() {
return ApiService.getUserProfiles().then(response => {
this.userProfiles = response.data
})
},
getTickets() {
return ApiService.getTickets().then(response => {
this.tickets = response.data
})
},
load() {
Promise.all([
this.getUserProfiles(),
this.getTickets()
]).then(data => {
this.assignNames();
this.isBusy = false;
});
},
assignNames(){
const tickets = this.tickets;
for (let i = 0; i < this.tickets.length; i++) {
if (tickets[i].assigned_to !== null) {
const result = this.userProfiles.filter(profile => {
return profile.uid == tickets[i].assigned_to
})
tickets[i].assigned_to = result[0].firstname + ' ' + result[0].lastname
}
}
}
}

VueJS: setInterval method not working properly

Please tell me what am i doing wrong? I want to active 'cloth' update every 2 sec. Still learning vue. Thanks
data() {
return {
clothes: ['t-shirts', 'sneakers', 'jackets'],
count: 0,
cloth: ''
}
},
methods: {
startInterval() {
setInterval(() => {
this.cloth = this.clothes[this.count]
this.count++
if (this.count >= this.clothes.length) {
this.count = 0;
}
}, 2000)
}
}
Vue has a life cycle that you can leverage to complete this objective. You can hook into the created function and execute your interval within:
created() {
this.startInterval()
},
This is not a method. It will be a sibling to your data and method properties.

Vue.js | Filters is not return

I have a problem.
I am posting a category id with http post. status is returning a data that is true. I want to return with the value count variable from the back. But count does not go back. Return in function does not work. the value in the function does not return from the outside.
category-index -> View
<td>{{category.id | count}}</td>
Controller File
/**
* #Access(admin=true)
* #Route(methods="POST")
* #Request({"id": "integer"}, csrf=true)
*/
public function countAction($id){
return ['status' => 'yes'];
}
Vue File
filters: {
count: function(data){
var count = '';
this.$http.post('/admin/api/dpnblog/category/count' , {id:data} , function(success){
count = success.status;
}).catch(function(error){
console.log('error')
})
return count;
}
}
But not working :(
Thank you guys.
Note: Since you're using <td> it implies that you have a whole table of these; you might want to consider getting them all at once to reduce the amount of back-end calls.
Filters are meant for simple in-place string modifications like formatting etc.
Consider using a method to fetch this instead.
template
<td>{{ categoryCount }}</td>
script
data() {
return {
categoryCount: ''
}
},
created() {
this.categoryCount = this.fetchCategoryCount()
},
methods: {
async fetchCategoryCount() {
try {
const response = await this.$http.post('/admin/api/dpnblog/category/count', {id: this.category.id})
return response.status;
} catch(error) {
console.error('error')
}
}
}
view
<td>{{count}}</td>
vue
data() {
return {
count: '',
}
},
mounted() {
// or in any other Controller, and set your id this function
this.countFunc()
},
methods: {
countFunc: function(data) {
this.$http
.post('/admin/api/dpnblog/category/count', { id: data }, function(
success,
) {
// update view
this.count = success.status
})
.catch(function(error) {
console.log('error')
})
},
},