Pokreniseweb
Pokreniseweb

Reputation: 165

Is it possible to simulate click on router-link element via another function in vue

Is there a way to simulate click event on router-link element in vue. I put router-link element in my carousel because in there I have access to movie object which I need for to pass router-link params, but in there it is very hard to styled it properly, so I will use button outside of carousel and when clicked trigger a function to simulate click on router-link. Eventually I will hide router-link element and use only button from which I am passing click event to function doing the simulation. I am new to vue so please have mercy on me:)

Here is the code

 <v-carousel-item
        style="cursor:pointer"
        v-for="movie in popularMovies"
        :key="movie.title"
        :src="apiUrl + movie.poster_path"
      >
        <div class="carousel-title">
          <p>{{movie.title}}</p>
        </div>
        <router-link 
        :to="{ name: 'MovieDetails', params: { id: movie.id }}">
        VIEW MORE</router-link>
      </v-carousel-item>
    </v-carousel>
    <div style="text-align:center;">
      <v-btn @click="loadRouterLink">VIEW DETAILS</v-btn>
    </div>

and method

methods: {
    ...mapActions(["fetchPopularMovies"]),
    loadRouterLink () {
      //do something here to simulate click on router-link element
    }
  },

Upvotes: 3

Views: 2039

Answers (1)

eli chen
eli chen

Reputation: 878

just like this

loadRouterLink (movieId) {
    this.$router.push({ name: 'MovieDetails', params: { id: movieId }})
}

please note i added a movieId paramter to loadRouterLink function. this is because the movieid is based on the v-for so the function should know what is the id (based on paramter - of course you can do it in other ways)

in your html you should send the correct id as paramter to this function

or you can do it in another way (same idea)

<v-carousel-item @click="movieId=movie.id"
        style="cursor:pointer"
        v-for="movie in popularMovies"
        :key="movie.title"
        :src="apiUrl + movie.poster_path"
      >
        <div class="carousel-title">
          <p>{{movie.title}}</p>
        </div>
        <router-link 
        :to="{ name: 'MovieDetails', params: { id: movie.id }}">
        VIEW MORE</router-link>
      </v-carousel-item>
    </v-carousel>
    <div style="text-align:center;">
      <v-btn @click="loadRouterLink">VIEW DETAILS</v-btn>
    </div>

and in the js part

{
    data(){
        return{movieId:0}
    },
    methods:{
         ...mapActions(["fetchPopularMovies"]),
    loadRouterLink () {
    this.$router.push({ name: 'MovieDetails', params: { id: this.movieId }})
    }
    }
}

source - https://router.vuejs.org/guide/essentials/navigation.html

Upvotes: 1

Related Questions