Vue Router configuration functions properly when accessed through URL directly

I need guidance on how to handle the routing setup in this specific scenario:

Below is the HTML structure that iterates through categories and items within those categories. The <router-view> is nested inside each category element, so when an item is clicked, it should only open within the corresponding category.

<ul>
    <li v-for="cat in categories">
        <ul>
            <li v-for="business in filteredByCat">{{business.name}}</li>
        </ul>
        <router-view v-if="..."></router-view>
    </li>
</ul>

The defined routes are as follows:

{
      path: '/businesses',
      name: 'Directory',
      component: Directory,
      children: [{
        path: ':listing',
        name: 'Listing',
        component: Listing
      }]
    }

Visualization:

https://i.stack.imgur.com/3V9KD.png

How can I pass the data of the clicked item to the router-view? I've tried using props but realize it may not work if the user accesses details directly via URL.

I attempted fetching the item like this:

methods: {
    finalItem ($route) {
      var match = this.businesses.filter((business) => {
        return business.link === $route.params.listing
      })
      return match[0]
    }
  }

This method doesn't seem to be effective. Is there an alternative approach to passing the data in a way that retains even when accessing details directly? This is my main concern. (I understand the repetitive use of <router-view> is not ideal coding practice, but I'm unsure how to address this given my current layout. Open to suggestions on improving this as well.)

Answer №1

The way in which you are utilizing the router-view could be simplified by just inserting a component instead. Using multiple router-views is quite common, contrary to what @varbrad mentioned. Child routes work well.

What's not so ordinary is employing multiple router-view's within a single component. Your desired UI closely resembles that of Netflix. If you observe their approach, you'll notice they pass a movie ID (business id/shortname) as "jbv" and a row number (category name) as "jbr" through the route query.

You can replicate this behavior in your component:

I don't have visibility into what filteredByCat entails, but based on your current setup, it seems like it would display the same businesses for each category. Consider trying something like this:

computed:{
  businessesByCategory(){
     let dictionary = {};
     this.businesses.forEach(business=>{
       business.categories.forEach(category=>{ // assuming each business has an array of categories
         dictionary[category] = dictionary[category] || [];
         dictionary[category].push(business)
       })
     })

     return dictionary;
  }
},
data(){
  return {
    activeBusiness:null
  }
},
methods:{
  setActiveBusiness(business){
    this.activeBusiness = business;
  },
  setUrlQuery(listing, category){
    this.$route.query.listing = listing;
    this.$route.query.category = category;
  },
  openListing(business, category){
    this.setActiveBusiness(business);
    this.setUrlQuery(business.link, category);
  }
}

-

<ul>
    <li v-for="cat in categories">
        <ul>
            <li 
              v-for="business in businessesByCategory[cat]"
              @click="openListing(business, cat)"
             >                     
                 {{business.name}}
            </li>
        </ul>
        <Listing :business="activeBusiness" v-if="$route.query.category == cat"></Listing>
    </li>
</ul>

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

Tips for navigating a dynamic viewport using scroll movement

Attempting to create a responsive page with two distinct sections at this example link including: Map View Table View Both of these views (table and map divs) need to be responsive without a hard-coded height, so the size of the map div adjusts automatic ...

When incorporating pinia with Vue, encountering an error with the decorator that says "Error: Unable to access 'useCoreStore' before initialization" may happen

While implementing the vue-facing decorator in my current project, I encountered an issue with setting up pinia. The structure of my component resembles the example provided here: I have verified that decorators like @Setup are functioning correctly, ind ...

What could be causing the CSS to not display properly on specific routes?

I'm facing an issue where CSS seems to be working fine for certain routes with node.js & express, but not for others. It's puzzling because the HTML file links to the same CSS file in both cases. For instance, CSS works perfectly for the route " ...

Confusion between modules and classes in Node.js when using CoffeeScript

I'm struggling to understand how to use Protoype in CoffeeScript, even though I am familiar with using it in standard Javascript with Node.js and modules. Imagine I have a file named mymodule.coffee: Module = {} class MyModule constructor: (para ...

Utilizing window.location.pathname in Next.js for precise targeting

Are you familiar with targeting window.location.pathname in NEXT.JS? I encountered a red error while using this code in Next.js const path = window.location.pathname console.log(path) // I am able to retrieve the pathname here Then { ...

Show an image in JPEG format using JavaScript within an img tag

Suppose http://example.com/image returns unique image data in response headers and the image itself. Each request to http://example.com/image generates a different image that is not related to the request itself. Besides the image, additional information s ...

Preserve present condition following a jQuery click event

I'm facing a challenge where I need to hide a button upon clicking another button, but the problem is that when the page refreshes, the hidden button becomes visible again. My objective is to keep it hidden even after refreshing the page and only reve ...

Blocking server.js in node.js can be achieved by modifying the code to prevent

Challenge Description In my server.js file, I have included a config file. This is how my server.js file looks: Includes some necessary imports Requires config.js -> makes an API call to get the configuration data using promises Starts the ser ...

Unable to make a successful POST request using the JQuery $.ajax() function

I am currently working with the following HTML code: <select id="options" title="prd_name1" name="options" onblur="getpricefromselect(this);" onchange="getpricefromselect(this);"></select> along with an: <input type="text" id="prd_price" ...

Module-bound changes in Vuex go unaffected by global alterations

In my project, I've implemented a UserDialog component that relies on a specific section of the Vuex state tree to determine whether it should be displayed. Here is a snippet of the component code: import { Component, Prop, Vue } from 'vue-prope ...

The Mystery of Two Nearly Identical Functions: One function is queued using Queue.Jquery, but the effects fail to work on this particular function. What could be causing this

In short, I am currently working on my first portfolio where I am utilizing Jquery to manipulate text. My goal is to have the text fade in and out sequentially. However, when using the queue function to load another function, the text within the span tag ...

Is there a more effective approach to managing an array of objects retrieved from an API call?

I'm attempting to extract an array of names from a JSON response that contains an array of objects, but I'm running into issues. When I try to print the array, it shows up empty. Is this the correct way to go about it? There don't seem to be ...

Transforming a Processing (cursor) file into an interactive webpage

I have created a custom cursor using Processing and now I want to incorporate it into my website. Is there a way to convert the cursor into a .java file so that I can include it in my HTML file? ...

Utilize jQuery to toggle classes on multiple elements in web development

I've been struggling to streamline this code I created for the website's navigation. As a novice in Javascript and jQuery, I would appreciate any help or advice. Thank you! Since the page doesn't reload, I have implemented the following met ...

Troubleshooting: Problems with AngularJS $http.get functionality not functioning as expected

I have a user list that I need to display. Each user has unread messages and has not created a meal list yet. I want to make two http.get requests within the main http.get request to retrieve the necessary information, but I am facing an issue with asynchr ...

Unexpected behavior observed in while loop with dual conditions

To break the while loop, I need two conditions to be met - res must not be undefined, which only happens when the status code is 200, and obj.owner needs to match a specific value I have set. Since it takes a few seconds for the owner on that page to updat ...

Errors in JavaScript are displayed when a React application is built for production

I have developed a client react application using create-react-app. It communicates with a node server that runs an express api. During development, everything was smooth sailing and I was preparing for deployment. After running npm run build, there were ...

Is there a way to use JavaScript to automatically open a URL at regular intervals?

List of URLs in JavaScript: var websites = ['https://www.google.com', 'https://www.msn.com', 'https://stackoverflow.com']; I have an array containing multiple website URLs. My goal is to open each URL in a new tab or window e ...

Utilize the power of jQuery for form validation by combining the errorPlacement and showErrors functions

I am currently attempting to implement validation using the Jquery .validate plugin. Unfortunately, I have encountered an issue where I am unable to utilize both the errorPlacement and showErrors methods simultaneously. If you'd like to see a demons ...

What could be causing the fourth tab to not show any data while the first three tabs are functioning as expected?

I've encountered an issue with my HTML tabs. While I can easily switch between the first three tabs and view their content, tab 4 doesn't seem to display its associated data. It's puzzling why tab 4 is not working when the others are functio ...