npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

vue-fetch-route

v0.1.7

Published

This npm package provides various helper methods to ease the pain of fetching, storing and reaccessing route based data with `vue`, `vuex` and `vue-router`.

Downloads

59

Readme

vue-fetch-route

This npm package provides various helper methods to ease the pain of fetching, storing and reaccessing route based data with vue, vuex and vue-router.

Build Status NPM version NPM downloads MIT License

Purpose

The package is intended to work in tandem with django-cms and its two plugins djangocms-spa and djangocms-spa-vue-js. However, these helpers might also come in handy for other environments and are not at all coupled to python or django.

Quickstart

  1. Install the module

    npm install -S vue-fetch-route 
  2. Register the plugin to your Vue instance

    import VueFetchRoute from 'vue-fetch-route';
    Vue.use(VueFetchRoute);
  3. Initialize vuex and use connect to register the plugin to your store. Please see also Route records - Additional fields

    const store = new Vuex.Store();
    const unsync = Vue.$fetchRoute.connect(store);
  4. Initialize vue-router and use decorateRecords to prepare your route records

        const myRoutes = [/* your route records */];
    
        const router = new VueRouter({
            routes: Vue.$fetchRoute.decorateRecords(myRoutes)
        });
  5. Init your app, use invokeFetch in your page components to initialize a data fetch

    const App = new Vue({
        store,
        router,
    }); 
        
    const PageComponent = {
        beforeRouteEnter(to, from, next) {
            const Fetched = Vue.$fetchRoute.invokeFetch(to);
            next(vm => {
                Fetched.then(data => {
                    vm.$set(vm.$data, 'routeData', data);
                });
            });
        },
        beforeRouteUpdate(to, from, next) {
            const Fetched = Vue.$fetchRoute.invokeFetch(to);
            Fetched.then(data => this.$set(this.$data, 'routeData', data));
            next();
        },
    };

Necessary polyfills

The plugin uses the URLSearchParams API internally to compile fetch and storage urls. You should add the url-search-params polyfill for MS Edge and Internet Explorer support. For detailed support tables, see the caniuse support table.

Route records - Additional fields

To enable automatic fetch, your RouteConfigs need a few more properties to work with this plugin. This is a full example with all the possible keys and values of an enhanced route:

const route = {
    'path': '/user/:username/dashboard', // basic vue-router property
    'name': 'user-dashboard', // basic vue-router property
    'component': UserDashboard, // basic vue-router property
    'api': {
        'fetch': { 
            // Provide the raw url under which the page data can be fetched
            'url': '/api/user/:username/dashboard',
            // This query object will be added to the url before fetching
            'query': {
                // Load those partials when navigating to this route
                'partials': ['menu', 'footer'],
            }, 
            // Allow or disallow caching the route data in the vuex store 
            'useCache': true 
        },
        // It's possible to prefill one or all of the pages with initial data to avoid fetching altogether!
        'fetched': {
            'response': {
                // These are basic page data that can be inserted into the page
                'data': { 'title': 'Welcome back, robomaiden!' },
                // This is a special object that contains shared component data like a menu or a footer
                'partials': {
                    'menu': { 'home': '/' },
                    'footer': { 'text': 'say hello to the footer' },
                }
            },
            // In order to store the response under the right url, we need params and the query:
            'params': { 'username': 'robomaiden' }, 
            'query': {  
                'partials': ['menu', 'footer'], 
                'favs': 'pokémon'
            }
        } 
    },
}

A word about partials

Partials are intended to work as data equivalents to static placeholders from django-cms. Those are cached separately and won't be requested a second time. Using partials is completely optional.

Vuex state

Please note that the plugin's default vuex namespace is vue-fetch-route. So to access the plugin store you need to load the getters like this:

const MyVueComponent = {
    computed: {
        ...mapState('vue-fetch-route', [/* properties */]),
    },
};

You can change this name in the plugin config.

isLoading

When a fetch request is pending the plugin's vuex module flag isLoading is set to true:

<template>
    <my-vue-component>
        <my-vue-loader v-if="isLoading"></my-vue-loader>
        <div v-if="!isLoading">
              <h1 v-text="routeData.title"></h1>  
        </div>            
    </my-vue-component>
</template>

<script>
    const MyVueComponent = {
        computed: {
            ...mapState('vue-fetch-route', ['isLoading']),
        },
    };
</script>

partials

If you have shared data on multiple pages, for example a menu or a footer, you may want to store their data centrally. For this purpose, you can use the special partials object:

<template>
    <my-vue-menu v-if="partials.menu">
        <!-- menu content -->          
    </my-vue-menu>
</template>

<script>
    const MyVueMenu = {
        computed: {
            ...mapState('vue-fetch-route', ['partials']),
        },
    };
</script>

routes

This routes dictionary contains the stored promises of visited pages. You shouldn't need to interact with it by yourself as accessing them is already done automatically via the invokeFetch method in your page components.

Plugin config

log

Log method to gain some insights about route navigation and data storing

Default: window.console.log

warn

Warn method to notify about possible errors

Default: window.console.warn

fetch

Method used to invoke when fetching data

Parameters

Returns Promise A promise resolving with the route data

Default

    const config = {
        fetch(url) {
            return new Promise((resolve, reject) => {
                window.fetch(url).then(
                    response => resolve(response.json()),
                    error => reject(error)
                );
            });
        },
    };

ignoredQueryParams

A list of query params that are ignored when defining the key to store the data. This is important to avoid storing data copies of the same route under different keys.

Default: []

vuexModule

The name that is used to register the vuex module to the store

Default: vue-fetch-route

API

connect

Wire up a vuex store with the app

Parameters

  • store Object A vuex store containing the router module

Returns Function Unsync function

decorateRecords

Route config creation helper

Parameters

  • records Array A route record array describing a list of available routes (optional, default [])
  • middlewares Array A list of middlewares to apply to each route (also recursively) (optional, default [])
  • parents Array The records' parental hierarchy, the first item being the oldest (optional, default [])

Returns Array The enhanced route records, ready for being used by vue-router

compareRecords

Compare two route definitions, ignoring irrelevant information such as hash

Parameters

  • to Object A route record describing the previous location
  • from Object A route record describing the next location

Returns boolean A flag indicating if two records are identical

invokeFetch

Start a fetch request

Parameters

  • route Object A route descriptor object
    • route.meta Object The route's meta property
    • route.params Object All currently active params
    • route.query Object The currently active query object

Returns Promise A promise returning route data of a page