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

Is there a way to determine the names of the functions that are being called?

I'm working on mastering Google Development Tools. Is there a way to determine which specific functions, especially those in Javascript, are needed before a page can load successfully? ...

Troubleshooting Recursive Logic Problem with hasOwnProperty in JavaScript and JSON

JSON data with a specific problem highlighted by the comment // doesn't get parsed currently: var oarsObject = [{ "coordinateReferenceSystem": "26782,15851 <-- not in a value", "positionReferenceType": "geogWgs84", "geogWgs84": ...

An SQL query that functions flawlessly in STUDIO 3T, yet fails to execute in Express.js

I encountered a puzzling situation where a query that functions perfectly in STUDIO 3t fails to retrieve any data in express js. Below is the code comparison: STUDIO 3t Query: db.getCollection("tickets").find({ $and: [ {"TCKT_CRTE_DTTM" : { ...

What distinguishes submitting a form from within the form versus outside of it?

When the code below, you will see that when you click btnInner, it will alert 'submit', but clicking btnOuter does not trigger an alert. However, if you then click btnInner again, it will alert twice. Now, if you refresh the page: If you first ...

Encountering an error code of 500 when executing the createIndex function in Pouch

I'm currently working on setting up a basic index, and I have the following code snippet: currentDB.createIndex({ index: { fields: ['name'] } }).then((result) => { }).catch((error) => { }) However, when I try to r ...

Locate the index of each distinct element within the array

Let's define an array called 'arr' with some elements: [7, 9, 30, 40, 50, 8, 1, 2, 3, 40, 90,2, 88,1] We also have another output array defined as: [0, 1, 2, 3, 4, 5, 6, 7, 8 ,10, 12] I stored this code snippet on a javascript ...

Counting the number of key-value pairs for a specific key in a JSON data can be achieved by implementing

Is there a way to determine if __metadata and ItemToEkbeNav are the root elements for their children who have key-value pairs? I've attempted various methods such as Object.keys().length and Array.isArray(), but haven't been able to retrieve the ...

Creating nested directories in Node.js

I am attempting to accomplish the following task Create a function (in any programming language) that takes one parameter (depth) to generate folders and files as described below: At depth 0, create a folder named 0, and inside it, create a file with its ...

Utilizing JSON API filtering within a Next.js application

Recently delving into the world of coding, I've embarked on a personal project that has presented me with a bit of a challenge regarding API filtering. My goal is to render data only if it contains a specific word, like "known_for_department==Directin ...

Discovering the number of words, extracting specific words, and transferring them to a URL using JavaScript

I have retrieved a document from a URL and saved the response. There are 3 tasks I need to accomplish here:- Calculate the word count in the document. Gather information for the top 3 words (sorted by frequency) including synonyms and parts of speech. A ...

What is preventing the function from successfully compiling text from various files that are uploaded using the HTML5 file reader into an array?

My current challenge involves attempting to upload two text files using the HTML 5 file reader. While I can successfully get the files into an array, encountering difficulty arises when trying to return that array from the function. One solution could be ...

Protractor functions perfectly on localhost, but encounters a Timeout error when used remotely - the asynchronous callback was not executed within the specified timeout period

Running protractor protractor.conf.js --baseUrl=http://localhost:4200/ executes successfully by filling data, validating elements, etc. However, when attempting to test the same website through a remote URL protractor protractor.conf.js --baseUrl=http://t ...

Testing if the App properly renders results in an error message: "No element found with the text: Profil"

I am struggling with testing Jest as I lack experience in this area. Specifically, I need to determine whether the App component is being rendered successfully. However, my test cases are failing. Upon checking the console log, I encountered the following ...

The Right Way to Set Up Form Data in VueJS

Currently, I am facing an issue with a component that renders a form and pre-fills the fields with data retrieved from an ajax request. The problem lies in my desire to edit existing fields and simultaneously add new fields for submission. To accomplish t ...

How to convert an array of keys and an array of values into an array of objects using JavaScript

My question is similar to the one found here: Merging keys array and values array into an object using JavaScript However, I am unable to find a solution for my specific scenario. If I have these two arrays: const keys = ['x', 'y', &ap ...

Creating a JavaScript function in Selenium IDE specifically for today's date

Just starting out with Selenium IDE and looking to build a set of regression scripts for our department. Trying to insert today's date plus 180 days into a field using a JavaScript function. If anyone can guide me on how to write this function, I wou ...

Prevent the automatic inflation of bubbles on the D3 World Map

Currently, I am developing a D3 world map with a zoom feature that allows users to zoom in up to the boundary level of any country or county by clicking on it. I have successfully added bubbles that point to various counties in Kenya, and these bubbles en ...

Choose only the options that are present in both arrays

I am working on creating a multiple select feature that displays all nodes, but only checks the ones that are present in 2 arrays. My front end is developed using Angular 8 and TypeScript. private mountSelect(nodesInRelation, lineApiKey) { console.lo ...

Running a Python script using Node.js

I'm having trouble running a machine learning script from my node.js application using the child-process core module as described here However, I am unable to receive any output from script.stdout.on. The versions I am using are Node v12.5.0 and pyt ...

Tips for monitoring Google Analytics/ Adwords Conversions within VueJS

I have developed a VueJS application in which users submit a form, and the data is sent to the server using Vue-resource. I want to track this as a conversion for Google Analytics. Google has provided me with a script that needs to be placed on a page lik ...