Quickly browse through the options (Vuex, routing) and modify the routing based on the selected value from the

Seeking advice on dynamically changing routing details in a search component based on user selection from a dropdown menu.

Home.vue Components

<h4>Search for {{searchObj.whatSearch}}</h4>
          <input type="text" placeholder="Search..." v-model='searchObj.searchString'>
            <select name="searchOption" id="searchOption" v-model='searchObj.whatSearch'>
              <option :value="'songs'">Song</option>
              <option :value="'artists'">Artist</option>
              <option :value="'albums'">Album</option>
            </select>
        </div>
        <button @click="getMusic(searchObj)">Searchk</button>


//importing the Searchcomponent here
        <div v-if="ifSearched">
          <search-result/>
        </div>

<script>
import SearchResult from './SearchResult.vue'

export default {
    
  data(){

    return{
    ifSearched: false,
      searchObj:{
        whatSearch: 'songs',
        searchString: '',
      },
    }
  },

  components:{
    SearchResult,
    
  },

  methods:{

      async getMusic(searchObj){
        this.ifSearched = true
        return await 
    this.$store.dispatch('fetchYouTubeApi', searchObj)                
      },
  },

  computed:{
    getYTMusic(){
      return this.$store.state.musicResult.content
    }
  }
}
</script>

Now, I am trying to modify the router link in my searchComponent based on:

<select name="searchOption" id="searchOption" v-model='searchObj.whatSearch'>
              <option :value="'songs'">Song</option>
              <option :value="'artists'">Artist</option>
              <option :value="'albums'">Album</option>
            </select>

I want to change the router link to different routes. In my SearchResult component:

<div>
        <h3>Search Result</h3>
        <div id="searchLoop" 
        v-for="(result, videoId) in getYTMusic" 
        :key="videoId">
        <router-link type="button" :to="`/musicdetails/${result.browseId}`"> 
            <p>{{result.name}}</p>    
        </router-link>            
        </div>
    </div>

<script>
export default {
    computed:{
        getYTMusic(){
           return this.$store.state.musicResults.content
     }
    }
}
</script>

If the user selects songs, for example, I want to route to:

<router-link type="button" :to="`/SongDetails/${result.browseId}`"> 
//or /ArtistDetails
//or /AlbumDetails

Is it possible to achieve this using v-if condition?

Answer №1

I devised a straightforward method for switching between different destinations using a property within the same <router-link> element. The structure of the HTML could be like this:

<div>
  <select name="searchOption" id="searchOption" v-model="testProp">
    <option v-for="link in routerLinks" :value="link.value" :key="link.value">{{link.label}}</option>
  </select>
</div>
<div>
  <router-link type="button" :to="`/${testProp}`">
    <p>{{testProp}}</p>
  </router-link>
</div>

To implement this example, the script portion would require these properties:

export default {
  data() {
    return {
      testProp: "",
      routerLinks: [
        { label: "Songs", value: "songs" },
        { label: "Artists", value: "artists" },
        { label: "Albums", value: "albums" }
      ]
    }
  }
}

In this illustration, the value in routerLinks signifies the segment of the URL that you wish to toggle based on the selected option. The chosen option is saved in testProp, which is then utilized in <router-link> as the :to value, while the label from routerLinks is employed within <router-link>.

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 method to apply the background-color of the parent element based on the child class in CSS?

Is there a method to change the parent's background color based on the child's class using CSS? Here is the sample code snippet: Sample Code If the child has a class of red, the parent should have a red background. If the child has a class of ye ...

Updating nested objects: A guide on how to effectively modify complex

I am trying to utilize the $push method in order to insert an object into a nested array, but I am struggling to dynamically access the correct object inside the array. Allow me to provide a clearer explanation by showcasing the code. Here is my Schema: ...

Retrieving the most recent selections made in a quiz using jQuery

My current project involves creating a dynamic quiz to improve my knowledge of Javascript, jQuery, HTML, and CSS. I recently encountered an issue with implementing a back button feature. The back button allows users to review their last answer and make cha ...

Efficiently manage and switch between multiple VueJS applications on a single page without any redirection needed

In the process of developing an extensive project that consists of multiple VueJS applications, each with its own router and store. Access to these applications is through URLs like: https://baseurl.com/app1/#/ https://baseurl.com/app2/#/ https://baseurl ...

Identifying all elements with querySelectorAll and monitoring events with

I am currently attempting to modify this demonstration for page transitions triggered by clicking on links with a shared class. Despite following @ourmaninamsterdam's suggestion here, I am facing difficulties in getting the transitions to work. Can yo ...

Issue with owl-carousel and Ajax integration

I am experiencing an issue with implementing ajax in my page which contains owl-carousel. Here is the code: Controller: public int Getmembers() { return db.Teams.Count(); } } The View : <script> $(document).ready(funct ...

Is there a way to change my cursor to a pointer finger when hovering over my box?

<script type="text/javascript"> function draw() { var canvas = document.getElementById('Background'); if (canvas.getContext) { var ctx = canvas.getContext('2d'); ctx.lineWidth = 0.4 ctx.strokeRect(15, 135, 240, 40) Is there a w ...

Issues with jQuery fundamentals

For a while now, I've been grappling with jQuery. It's undeniably powerful and offers a plethora of fantastic capabilities. However, my struggle lies in the fact that I tend to incorporate multiple jQuery features simultaneously. For example, on ...

Integrate several YouTube players within a tabbed angular-ui system. Looking to incorporate a collapse feature

I come to you with a humble request for guidance. As a newcomer to Angular and someone who has never ventured into the realm of the YouTube JavaScript API, I am well aware that I may be making errors without even realizing it. While my code appears to be f ...

The utilization of the JavaScript null coalescing operator ?? resulted in a crash of the .NET JS minifier/bundler

I'm facing an issue with my code where using the ?? operator causes a crash in the MVC built-in bundler/minifier. The problematic line is: span.textContent = typeof (info) === 'object' ? info.column.caption ?? info.column.dataField : info; ...

What steps can be taken to avoid including empty tasks in React code?

Is there a way to prevent my application from adding empty tasks? Below is the code snippet for adding a new task to an array. How can I implement a condition to block the addition of empty tasks? This application follows Mozilla's guidelines for a R ...

Instructions on how to showcase a standard text within a designated text container

I am currently facing an issue with a textarea or textbox that is dynamically receiving URLs from a database. The textbox is displaying the full URL address, which is not visually appealing. I would like to replace this with some generic text such as "cl ...

Erase a set of characters with the press of the backspace key (JavaScript)

Within my textarea, I have lines that start with a number and a period: <textarea autoFocus id="text-area"wrap="hard" defaultValue ={this.state.textAreaVal} onKeyUp={this._editTextArea}/> For example: Line 1 Line 2 Line 3 I've created a ...

Troubleshooting Jqgrid Keyboard Navigation Problem

Here is a link to the jsfiddle code snippet. Upon adding jQuery("#grid").jqGrid('sortableRows'); into my JavaScript code, I encountered an issue where keyboard navigation no longer worked after sorting rows Below is the JavaScript code snippet: ...

Error message: "Uncaught TypeError: Cannot set property 'state' of undefined in ReactJS"

I am encountering an issue while trying to update the state within my React function. The error message I receive indicates: "Cannot read property 'setState' of undefined." Reviewed below is my code where I have initialized the state in the cons ...

Is it possible to establish the page state upon loading (in the context of a GET request

At present, my navigation bar is set up to utilize AJAX for loading new pages and window.pushState() in order to update the URL when the AJAX call is successful. I've come to realize that it's crucial to push the page state during GET requests s ...

The variable module.exports is currently undefined

I've been struggling to retrieve values returned from a module.exports function within a separate custom module. Despite researching various sources and trying different methods for over 10 seconds, I still haven't found a solution. If you'r ...

Ways to display an error notification alongside another message

I have set up a validation directive that requires users to check a box. If the checkbox is left unchecked, an error message will be displayed. However, I am facing an issue where the message overlaps with the checkbox text. https://i.sstatic.net/iTKoo.jp ...

Having trouble fetching RSS XML data from external websites using the Axios and Vue.Js combination

I have been encountering an issue with utilizing the RSS XML feeds from multiple websites for my Web App. I attempted to incorporate the Axios function as shown below: axios.get('https://www.15min.lt/rss/sportas') .then((response) => { ...

Node.js encountering issue with printing an array

Here is the code snippet from my routes file: router.get('/chkjson', function(req, res, next) { req.getConnection(function(err,connection){ var ItemArray = []; var myset = []; var query = connection.query('SELEC ...