I would like to change page when the user scrolls down - vuejs2

methods: {
handleScroll () {
window.onscroll = () => {
if (window.scrollY > 0) {
alert('toto');
}
}
}
},
created () {
window.addEventListener('scroll', this.handleScroll);
},
destroyed () {
window.removeEventListener('scroll', this.handleScroll);
},
This code does not work.
It is also triggered when the page loads.
Besides, I would like this code to be active only on the homepage.
Thanks for your help.

methods: {
handleScroll () {
window.onscroll = () => {
if (window.scrollY > 5 && this.$route.name ==="Accueil" ) {
this.$router.push({name:'Offres'})
}
}
}
},
With this code, it's ok

Related

Vuejs 3 - Unable to remove resizeEvent

I have resize event in my mounted() works well.
data() {
return {
...
eventHandler: null,
};
},
mounted() {
this.eventHandler = window.addEventListener("resize", () => {
console.log("resize");
});
},
but when I tried to remove the resize listener on unmount()
beforeUnmount() {
console.log("unmonunted");
window.removeEventListener("resize", this.eventHandler);
},
the resize event is still firing
Anyone know how to solve this?
window.addEventListener returns undefined, not the event handler function.
You should change your code like this:
data() {
return {};
},
mounted() {
window.addEventListener("resize", this.eventHandler);
},
beforeUnmount() {
window.removeEventListener("resize", this.eventHandler);
},
methods: {
eventHandler() {
console.log("resize");
}
}

How do you know if you can't go back VueJS

I would like to write a method that links to the homepage if I can't go back.
a code a bit like that:
if (**router.back.length == 0**){
router.push({name:"Home"})
}else {
router.back();
}
}
the problem is i dont know how to tell if the .back () is possible or not.
I am currently on a pageNotFound, I go to the current page using the following redirect
path: "/:catchAll(.*)",
name: "PageNotFound",
component: () =>
import(/* webpackChunkName: "NotFound" */ "#/views/PageNotFound.vue")
}
Thanks for your help!
Had similar case once. Try something like this (treat it like a pseudo code):
data: () => ({
fromRoute: null
}),
beforeRouteEnter (to, from, next) {
next(vm => {
vm.fromRoute = from;
})
},
methods: () {
handleBack() {
if (!this.fromRoute.name) {
router.push({name:"Home"});
} else {
router.back();
}
}
}
More info here: https://forum.vuejs.org/t/how-to-go-back-or-go-home/30242/3
Use this code to achieve the desired result. Make sure you are using [Named Routes][1].
export default {
data() {
return {
fromRoute: null
};
},
beforeRouteEnter(to, from, next) {
next((vm) => {
vm.fromRoute = from;
});
},
methods: {
goBack() {
if (!this.fromRoute.name) {
this.$router.push("/");
} else {
this.$router.back();
}
},
},
};
[1]: https://router.vuejs.org/guide/essentials/named-routes.html
By looking in the VueJs doc I found the solution
goBack() {
if(this.$router.getRoutes().length==0){
this.$router.push({name:"Home"})
}else{
this.$router.back();
}
}
https://router.vuejs.org/api/#router-onready

can't write api method in data() vue

I want USD to be taken from api which function I've in methodsbut how can I write it ?
data(){
return {
posts: 1,
USD:changeCurrency()
}
},
methods: {
changeCurrency: function () {
axios.get('http://data.fixer.io/api/latest?access_key=509c9d50c1e92a712be9c8f1f964cf67')
.then(response => {
this.posts = response.data.rates.GEL.toFixed(3)
})
}
That is not how data is supposed to be used.
You can call changeCurrency in mounted or in the component itself #click="changeCurrency"
{
data() {
return {
posts: 1,
// USD:changeCurrency()
};
},
mounted() {
// you could call here instead
this.changeCurrency();
},
methods: {
changeCurrency: function () {
axios.get('http://data.fixer.io/api/latest?access_key=509c9d50c1e92a712be9c8f1f964cf67')
.then(response => {
this.posts = response.data.rates.GEL.toFixed(3);
});
}
}
}

How to stop the video if the slide has changed?

I need to stop the video when the slide is changed. The current code reacts to changing the variable, but does not stop the video. I use Clappr ^0.3.3, Vue-cli ^3.5.0 and Swiper ^4.5.0.
I change the boolean value to use it for the trigger in the player:
data: () => ({
slider_is_move: false,
}),
After request:
.then(() => {
// init slider
new Swiper('.content__slider', {
// Note: I removed extra options
on: {
slideChange: function () {
this.slider_is_move = true; // if slide is change
setTimeout(() => {
this.slider_is_move = false; // set the previous value
}, 1500);
}
}
});
// 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,
events: {
onPlay: () => {
setInterval(() => {
if (this.slider_is_move === true) {
this.pause();
}
}, 1000);
}
}
});
}
}
});
If I add a console.log(), the code will work as it should, but it will not stop the video.
onPlay: () => {
setInterval(() => {
if (this.slider_is_move === true) {
this.pause();
}
}, 1000);
}
To make the video stop when you change the slide, you need to add a few lines in the code:
add name to object
let player_video = new Clappr.Player...
and pause it
player_video.pause();
You should watch the data attribute slider_is_move, and react to any changes in the state.
watch: {
slider_is_move: {
handler(nowMoving) {
if (nowMoving) {
this.pause();
}
},
}
}

Computed property "main_image" was assigned to but it has no setter

How can I fix this error "Computed property "main_image" was assigned to but it has no setter"?
I'm trying to switch main_image every 5s (random). This is my code, check created method and setInterval.
<template>
<div class="main-image">
<img v-bind:src="main_image">
</div>
<div class="image-list>
<div v-for="img in images" class="item"><img src="img.image"></div>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'Item',
data () {
return {
item: [],
images: [],
}
},
methods: {
fetchImages() {
axios.get(`/api/item/${this.$route.params.id}/${this.$route.params.attribute}/images/`)
.then(response => {
this.images = response.data
})
.catch(e => {
this.images = []
this.errors.push(e)
})
},
},
computed: {
main_image() {
if (typeof this.item[this.$route.params.attribute] !== 'undefined') {
return this.item[this.$route.params.attribute].image_url
}
},
},
watch: {
'$route' (to, from) {
this.fetchImages()
}
},
created () {
axios.get(`/api/item/${this.$route.params.id}/`)
.then(response => {
this.item = response.data
})
.catch(e => {
this.errors.push(e)
})
this.fetchImages();
self = this
setInterval(function(){
self.main_image = self.images[Math.floor(Math.random()*self.images.length)].image;
}, 5000);
},
}
</script>
Looks like you want the following to happen...
main_image is initially null / undefined
After the request to /api/item/${this.$route.params.id}/ completes, it should be this.item[this.$route.params.attribute].image_url (if it exists)
After the request to /api/item/${this.$route.params.id}/${this.$route.params.attribute}/images/ completes, it should randomly pick one of the response images every 5 seconds.
I'd forget about using a computed property as that is clearly not what you want. Instead, try this
data() {
return {
item: [],
images: [],
main_image: '',
intervalId: null
}
},
methods: {
fetchImages() {
return axios.get(...)...
}
},
created () {
axios.get(`/api/item/${this.$route.params.id}/`).then(res => {
this.item = res.data
this.main_image = this.item[this.$route.params.attribute] && this.item[this.$route.params.attribute].image_url
this.fetchImages().then(() => {
this.intervalId = setInterval(() => {
this.main_image = this.images[Math.floor(Math.random()*this.images.length)].image;
})
})
}).catch(...)
},
beforeDestroy () {
clearInterval(this.intervalId) // very important
}
You have to add setter and getter for your computed proterty.
computed: {
main_image: {
get() {
return typeof this.item[this.$route.params.attribute] !== 'undefined' && this.item[this.$route.params.attribute].image_url
},
set(newValue) {
return newValue;
},
},
},