Guide on implementing router-link within a select option dropdown in a Vue.js application

a.vue

<template>
  <div>hi i am component 1</div>
</template>

<script>
export default {
  name: "a",
};
</script>


b.vue

<template>
  <div>hi i am component 2</div>
</template>

<script>
export default {
  name: "b",
};
</script>
const router = new VueRouter({
  mode: "history",
  routes: [
    {
      path: "/a",
      name: "a",
      component: a
    },
    {
      path: "/b",
      name: "b",
      component: b
    }
  ]
});
<template>
  <div class="select">
    <select name="format" id="format" v-on:change="changeRoute($event)">
      <option selected>Settings</option>
      <option value="">a</option>
      <option value="">b</option>
    </select>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  methods: {
    changeRoute(e) {
      this.$router.push("/a" + e.target.value);
      // this.$router.push("/b" + e.target.value); not working....
    },
  },
};
</script>

How to navigate to a different component when selecting a value from the dropdown in Vue.js using router link.

Currently, I have an issue where I can redirect to a component using router-link by setting the click event in the select element.

Within the select element, there are two options named "hello" and "hlll". Both options navigate to the same page. However, I need to set a different component for each option.

Answer №1

Code Troubleshooting Tips:

Main.vue

  • Ensure that you include
    <router-view></router-view>
    in your Main.vue file to properly manage the routing section.

GreetingsWorld.vue

  • Remember to assign values like a and b for the options in the select element within this component.

Template

<select name="format" id="format" v-on:change="changeRoute($event)">
  <option selected>Settings</option>
  <option value="a">a</option>
  <option value="b">b</option>
</select>

You can listen for the change event within the component and handle navigation as follows:

methods: {
  changeRoute(e) {
    this.$router.push("/" + e.target.value);
  },
},

By setting values for each option, you will obtain a valid value for e.target.value during the change event.

Interactive Example

Answer №2

To incorporate your routes into a data object, follow these steps:

const Homepage = {
  template: '#homepage',
  data() {
    return {
      links: [{name: 'welcome', path: 'mycomponent'}, {name: 'greetings', path: 'othercomponent'}],
      selectedPath: null
    }
  },
  methods: {
    switchRoute() {
      this.$router.push(this.selectedPath);
    }
  },
}

const ComponentOne = {
    template: '#componentone'
};

const ComponentTwo = {
    template: '#componenttwo'
};

const paths = [
    { route: '', component: Homepage },
    { route: '/mycomponent', component: ComponentOne },
    { route: '/othercomponent', component: ComponentTwo }
]

const routerOptions = new VueRouter({
    paths
});

new Vue({
    routerOptions
}).$mount('#root');
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js"></script>
<script src="https://unpkg.com/vue-router"></script>
<script type="text/x-template" id="homepage">
  <div>
    <h2>Homepage</h2>
    <div class="selection">
      <select name="path" id="path" v-model="selectedPath" @change="switchRoute">
        <option :value="''" selected disabled>choose link below</option>
        <option v-for="(lnk, idx) in links" :key="idx" :value="lnk.path">
          {{ lnk.name }}
        </option>
      </select>
    </div>
  </div>
</script>

<script type="text/x-template" id="componentone">
  <div>
    <h2>mycomponent</h2>
    <router-link to="/">Homepage</router-link>
  </div>
</script>

<script type="text/x-template" id="componenttwo">
  <div>
    <h2>othercomponent</h2>
    <router-link to="/">Homepage</router-link>
  </div>
</script>

<div id="root">
    <h1>routing with choice</h1>
    <router-view></router-view>
</div>

Answer №3

To implement the change event handler, include $event, then utilize that parameter in the router link push method:

 <select name="format" id="format" v-on:change="changeRoute($event)">

 methods: {
   changeRoute(e) {
     this.$router.push('/'+e.target.value)
   }
 }
 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a unique type in Typescript that represents a file name with its corresponding extension

Is there a way for me to specify the type of a filename field in my object? The file name will consist of a string representing the name of the uploaded file along with its extension. For instance: { icon: "my_icon.svg" } I am looking for a ...

Execute a function that handles errors

I have a specific element that I would like to display in the event of an error while executing a graphql query (using Apollo's onError): export const ErrorContainer: React.FunctionComponent = () => { console.log('running container') ...

Why does Socket.IO seem to be registering two clients instead of just one when there is only one connection

When using my app, the user first lands on the home screen where they can select their username. They then proceed to another page and from there, navigate to the room entry page. The issue I'm facing is with a specific section of my code that update ...

Why is TypeScript unable to recognize package exports? (using CommonJS as the module system and Node as the module resolution)

I have an NPM package that is built for ESM and CJS formats. The package has a dist folder in the root directory, which contains: dist/esm - modules with ESM dist/cjs - modules with CJS dist/types - typings for all modules In the package.json file, there ...

Exploring the features of AngularJS, one can delve into the ControllerAs syntax

Currently, I am in the process of developing a directive and following the guidelines outlined in the John Papa style guide. In line with this, I have adopted the ControllerAs syntax approach and implemented a small directive as shown below: (function() { ...

Gradually returning to the top with Vuetify's smooth scroll feature

Looking for a way to make the scrolling back to the top of the page smoother on my website. The button I currently have in place does the job, but it's not as smooth as I would like. Any suggestions on how to improve this? I've checked similar q ...

Solving Mixed Content Issues in JavaScript

I'm attempting to retrieve information from OMDB API, but I'm encountering an issue with mixed content images. OMDB pulls its data from IMDB, which does not allow the use of https images. Therefore, all image sources must be prefixed with http. ...

What is the best method for storing a client-side token in nextjs 13 with the App Router update?

We are currently using a nextjs 13.5 web application. The new app router paradigm in Next.js 13 involves all components, including client components, going through their initial render on the server during a full page load (such as after a refresh). Accord ...

Organizing elements in JavaScript

By utilizing d3.nest, I've organized this list through element grouping from another list. array = [ {key: "6S", values: [{Id: "1234a", ECTS: 3}, {Id: "1234b", ECTS: 3}]}, {key: "7S", values: [{Id: "1534a", E ...

How to Retrieve Checkbox Values from Multiple Rows Using JavaScript

I have a variety of module rows that allow users to manage access rights by selecting specific options. My goal now is to extract the checked boxes from these checkboxes with the name "config{{$field->id}}". Below is the current functioning code. HTM ...

Error encountered when simulating the effect of calling 'insertPlayerData' function: ReferenceError - currentUserId has not been defined

PlayerList = new Mongo.Collection('players'); UerAccounts = new Mongo.Collection('user'); if(Meteor.isClient){ Template.leaderboard.helpers({ 'player':function(){ var currentUserId = Meteor.userId(); return Play ...

Retrieve the value of an object from a string and make a comparison

var siteList = {}; var siteInfo = []; var part_str = '[{"part":"00000PD","partSupplier":"DELL"}]'; var part = part_str.substring(1,part_str.length-1); eval('var partobj='+part ); console.log(par ...

Generating a Stream for FormData implementation

I am currently utilizing an API to import a CSV file. The CSV file is generated in memory from a String and then uploaded using the request module. However, I am encountering difficulties in creating a Readable Stream from the String. To resolve this issue ...

There was an error in reading the 'nativeElement' property in Angular's waveform library, resulting in a TypeError

This is the code I wrote, but it is showing an error: The waveform should be created, but the function to create the waveform is not working. startRecording() { this.mediaSectionVisible = false; if (!this.isRecording) { this.isRecording = t ...

Using AJAX to handle 404 errors in Slim PHP

When I attempt to retrieve data using AJAX in my Slim PHP application, I am encountering a 404 (Not found) error in the console. The specific error message is as follows: http://localhost:8888/Project/mods/public/edit-mod/ajax/get-categories?gameID=1 404 ...

Tips for including HTML tags within a string using node.js, express, and ejs

Currently, I am utilizing Node.js with Express and EJS for my project. My goal is to pass HTML tags within a string to the browser in the following manner: listRequests.forEach(function(key) { messages.push("You have a message from <b>" + key.us ...

Efficient method for quickly updating the color scheme of a grid of squares in JavaScript

Currently, I am developing a JavaScript game that features a 2D array of squares with background colors that update each frame. My current approach involves utilizing a borderless DOM table and setting the style.backgroundColor property of each cell every ...

How can I adjust the transparency in a JavaScript popup modal window for an ASP.Net GridView?

Recently, I added an 'onclick' event to every row of an asp gridview and the popup window that appears is functioning perfectly. Now, I'm interested in adding a transparency level to the body of the popup window for a translucent effect. Can ...

Changing focus to 'DIV' element without JQuery using Javascript and Angular's ng-click event

Instructions for using an Angular directive to set focus on a "DIV" element when clicked <a href="#" class="skipToContent" ng-click="showContent()" title="skip-to-main-content">Skip To Main Content</a> <div class="getFocus" role="button" ...

What causes this statement to consistently be incorrect?

I am in the process of developing a Q&A platform where users can vote on answers. I have assigned project.problem.upVoted to store a list of answers that the user has already upvoted. If an answer has already been voted on, the callback function for cl ...