Vue.js: Incorporating a client-side restful router using vue-router and a state manager

Trying to set up a client-side restful api with vue.js and vue-router where route params can be utilized to showcase a subset of a store's data into components. All the necessary data for the client is loaded into the store during initialization (not everything is displayed, including listeners to ensure data readiness).

Let's assume my store looks like this:

export default {
    "state": {
        "foosArray": [
            {
                "fooId": 1,
                "foo1": "bar",
                "foo2": "bar2"
            },
            {
                "fooId": 2,
                "foo1": "barbar1",
                "foo2": "barbar2"
            }
        ]
    }
}

Now, if there's a route that needs to display one of the foos based on a fooId in the route param into a component: /foo/:fooId

In my Foo.vue file:

<template>
    <h1>FooId: {{ fooId }}</h1><br>
    <h2>Foo1: {{ foo1 }}<h2><br>
    <h2>Foo2: {{ foo2 }}</h2>
</template>

<script>
    export default {
        "name": "Foo",
        data () {
            return {
                "fooId": -1,
                "foo1": "",
                "foo2": ""
            }
        }
    }
</script>

Query: What's the best method to achieve this? I've considered a few options, but none seem very optimal.

Option #1 - Computed Data: This is reactive, which aligns with using a library like vue.js, but could be computationally expensive.

Foo.vue

<template>
    <h1>FooId: {{ myFooId }}</h1><br>
    <h2>Foo1: {{ myFoo1 }}<h2><br>
    <h2>Foo2: {{ myFoo2 }}</h2>
</template>

<script>
    import Store from '../store/store.js'
    import _ from "underscore"

    export default {
        "name": "Foo",
        data () {
            return {
                "sharedState": Store.state
            }
        },
        computed: {
            "myFooId": function() {
                let oTempFoo = _.findWhere(this.sharedState.foosArray, { "id": this.$route.params.fooId });
                return oTempFoo ? oTempFoo["id"] : "";
            },
            "myFoo1": function() {
                let oTempFoo = _.findWhere(this.sharedState.foosArray, { "id": this.$route.params.fooId });
                return oTempFoo ? oTempFoo["foo1"] : "";
            },
            "myFoo2": function() {
                let oTempFoo = _.findWhere(this.sharedState.foosArray, { "id": this.$route.params.fooId });
                return oTempFoo ? oTempFoo["foo2"] : "";
            }
        }
    }
</script>

Option #2 - Using vue-router's data pipeline. This is simpler computationally, but might not be reactive to changes in the store's state.

<template>
    <h1>FooId: {{ fooId }}</h1><br>
    <h2>Foo1: {{ foo1 }}<h2><br>
    <h2>Foo2: {{ foo2 }}</h2>
</template>

<script>
    import Store from '../store/store.js'
    import _ from "underscore"

    export default {
        "name": "Foo",
        data () {
            return {
               "fooId": -1,
                "foo1": "",
               "foo2": ""
           }
       },
       route: {
           data: function (transition) {
               let oTempFoo = _.findWhere(Store.state.foosArray, { "id": this.$route.params.fooId })
               transition.next(oTempFoo);
           }
       }
   }
</script>

Thank you!

Answer №1

Incorporated the following solution which helps me avoid running computed data elements for each displayed value. I wish there was a simpler alternative, perhaps using a v-with="myFoo" in UberFoo so that I wouldn't need to utilize a sub-component.

UberFoo.vue

<template>
    <minor-foo :data="myFoo"></minor-foo>
</template>

<script>
    import Store from '../store/store.js'
    import MinorFoo from './MinorFoo.vue'

    export default {
        'name': 'UberFoo',

        data () {
            return {
                'sharedState': Store.foosArray
            }
        },

        'components': {
            'minor-foo': MinorFoo
        },

        'computed': {
            myFoo: function() {
                for ( var i = 0; i < this.sharedState.length; i++ ) {
                    if ( this.sharedState[i]["fooId"] == this.$route.params.fooId ) return this.sharedState[i];
                }

                return {
                    "fooId": null,
                    "foo1": null,
                    "foo2": null
                }
            }
        }
    }
</script>

MinorFoo.vue

<template>
    <h1>FooId: {{ data.fooId }}</h1><br>
    <h2>Foo1: {{ data.foo1 }}<h2><br>
    <h2>Foo2: {{ data.foo2 }}</h2>
</template>

<script>
    export default {
        'name': 'MinorFoo',

        'props': ['data']
    }
</script>

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

What could be causing my Bootstrap datepicker to malfunction?

A while ago, my Bootstrap datetimepicker component was functioning perfectly in my code. However, it has suddenly stopped working and I am seeking assistance to get it running smoothly again. Below is the HTML code snippet: <script src="https://cd ...

Navigating the way: Directing all TypeScript transpiled files to the build folder

I am currently working on a project using Angular2/Typescript, and I have the tsconfig.js file below: { "compilerOptions": { "module": "commonjs", "moduleResolution": "node", "target": "es5", "sourceMap": true, ...

Instructions for obtaining and assigning a reference to a recently cached associated object within the Apollo client InMemoryCache

My data consists of a set of interconnected items like this: book { id ... related_entity { id ... } } Once Apollo caches it, there are two separate cache objects. The related_entity field on book points to an EntityNode object. Everything ...

Having trouble registering Vuex modules? It could be because the namespaces are not being found or the getters.default property is

I've hit a roadblock while setting up Vuex modules for my latest project. I attempted to follow Chris Fritz's example of registering components in a more efficient manner, as demonstrated in this video: https://www.youtube.com/watch?v=7lpemgMhi0k ...

best practices for sending multiple requests using node js

I have a list of 4 URLs, each containing JSON data. How can I iterate through these URLs? Example: URLs = [ "", "", "", ""]; Each URL contains JSON data for one student as follows: { date: 08/05/2014 stude ...

What is the best way to establish a two-way connection between two arrays?

Within my application, there is an ItemsService responsible for fetching Items from the server and storing them as JSON objects in its cache. These Items may be displayed in various formats such as tables, graphs, or charts. For instance, when setting up ...

Using jQuery to enable scrolling and dynamically changing classes

I'm currently working on enhancing my website with a feature that changes the opacity of the first section to 0.4 when a user scrolls more than 400 pixels down the page. I attempted the following code without success: if($("html, body").offset().top ...

Mastering the Art of Accelerating getJSON Array Data

Currently, I am facing a challenge with retrieving a large array (4MB) of data from the server side. I have been utilizing the jQuery getJSON method to obtain the array data and display it on the browser. However, this process has proven to be quite slow ...

Employing double quotes within JSON keys or values can help enhance the readability and

Is there a way to include double quotes within my JSON data? I've been struggling with this issue. Below is the example of my JSON: "I": { "1: Vehicle Control:M": { "D2": { "VM": "3300.00", "VSD": ...

When the button is clicked, avoid the onclick event and display a modal. If "yes" is clicked, execute the onclick function

I am facing an issue with a page containing multiple input elements that all have similar structure. I want to show a modal before executing the onclick event, and only run the function when the "yes" button in the modal is clicked. However, the problem is ...

Having trouble accessing an AngularJS $scope variable because it is coming up as undefined

Currently, I am developing an Electron application using AngularJS for the frontend. Since node.js operates at the OS level while Angular runs at the client level, communication between the two is achieved through IPC (Inter-Process Communication) implemen ...

Is there a way to conceal a component using Twitter Bootstrap while having the ability to reveal it with the help of

Suppose I generate an HTML element in the following manner, <div id="unique-div" class="concealed">Hello, TB3</div> <div id="unique-div" class="hide-me">Greetings, TB4</div> <div id="u ...

What is the process of transforming a String into a Function prototype in JavaScript?

Recently, I encountered a JavaScript object containing key-value pairs with functions as values: var serial = { open: function(a, b) { // do something.. }, close: function (a,b) { // do something } } Due to certain requirements, I had ...

Resolved issue with sticky header movement after scrolling event

I've been working on a sticky header code, but I'm having trouble achieving a smooth scroll transition. The fixed header seems to jump after just one scroll. Here is the basic HTML structure: <div class="headerWrapper"> <div id="to ...

Ensure to wait for the user ID before accessing Firestore collections

Trying to wrap my head around rxJs and experimenting with using the where query in Firestore collection. However, I've run into an issue where the output of this collection is dependent on retrieving the user ID from Firebase Auth. Here's what I ...

What is the method to determine the number of keys that have the same value in a JavaScript object?

My goal is to achieve functionality similar to this: var data = [ { tag:'A', others:'Abc' }, { tag:'B', others:'Bbc' }, { tag:'A', others ...

Successful Mongoose query in Node.js, however the array remains empty even after using forEach loop. Issue with MongoDB integration

After performing a forEach inside an asynchronous method, I am trying to return an array of names. The issue is that despite the forEach working correctly, the array always ends up empty. On the website side, here is my request: function retrieveCharity( ...

Guide to custom sorting and sub-sorting in AngularJS

If I have an array of objects like this: [ { name: 'test1', status: 'pending', date: 'Jan 17 2017 21:00:23' }, { name: 'test2', sta ...

In my Node.js/Express.js application, I have a directory that holds various images. Whenever I attempt to view these images via their URL, I encounter a 404 error message

In my Node.js/Express js project, I have the following folder structure: root ----bin ----controllers ----middleware ----models ----node_modules ----public --------images ------------test.png ----routes ----views I am currently trying to determine the cor ...

Tips for adjusting the color of the white tick in Material UI Checkbox with React and JavaScript

I'm currently attempting to customize the default white tick (not the checkbox background!) and change it to a different color that I choose. While I have come across solutions for earlier versions of MUI and React, I am specifically looking for a sol ...