Tips for streamlining repetitive code in Vue 3 Composition API (such as router and store integration)

When using the Vue 3 Composition API, it is necessary for each view to include the following:

import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'


export default {
    setup() {
        const router = useRouter()
        const store = useStore()

        // ...
     }
}

Is there a more efficient way to declare these dependencies once, pass them to the created app, and then easily use them without having to redeclare them in every view within the app? In Vue 2, these were passed during initialization and could be accessed simply as this.$store / this.$router.

One potential approach involves utilizing global variables, although this method can lead to issues. For example, in the app.vue file, you could declare them like this:

import { useStore } from 'vuex'

export default {
    setup() {
        globalthis.store = useStore()

Then, the store variable would be accessible throughout the application.

Answer №1

The component instance is not accessible within the setup() function due to the fact that the component has not been initialized yet, resulting in the absence of a this context in the Composition API required for using this.$store.

To access the store/router variables in the setup() function without any additional imports, one potential solution is to assign them as global variables to window/globalThis (ignoring the common concerns related to global variables):

// router.js
import { createRouter } from 'vue-router'
export default createRouter({/*...*/})

// store.js
import { createStore } from 'vuex'
export default createStore({/*...*/})

// main.js
import router from './router'
import store from './store'

window.$router = router
window.$store = store

It's important to note that with Vuex 4 and Vue Router 4, the store and router can still be accessed using the Options API and within the template as $store and $router, respectively:

<template>
  <div>{{ $store.state.myProp }}</div>
  <button @click="$router.back()">Back</button>
</template>

<script>
export default {
  mounted() {
    console.log(this.$store.state.myProp)
    console.log(this.$router.currentRoute)
  }
}
</script>

Answer №2

Check out the amazing AutoImport Plugin created and maintained by Anthony Fu. This tool eliminates the need to manually add imports in your code, supporting Eslint and TypeScript.

Say goodbye to constantly scrolling between your logic and import statements - AutoImport reduces noise and allows you to focus on your domain.

The plugin also offers presets for vue, vue-router, vueuse, and more.

Shown below is a configuration example used in a Quasar project:

        AutoImport({
          // Specify targets to transform
          include: [
            /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
            /\.vue$/,
            /\.vue\?vue/, // .vue
            /\.md$/, // .md
          ],

          // Register global imports
          imports: [
            // Presets
            `vue`,
            `vue-router`,
            `@vueuse/core`,
            `quasar`,
            `vue-i18n`,
            // Custom
            {
              'quasar': [
                `setCssVar`,
                `colors`,
                `extend`,
                `EventBus`,
                `Notify`,
                `QItemSection`,
              ],
              'dedent': [
                [`default`, `dedent`],
              ],
            },
            {
              from: `vue`,
              imports: [`CSSProperties`],
              type: true,
            },
          ],
          // Enable auto import based on filename for default module exports within directories
          defaultExportByFilename: false,

          // Auto import for module exports within directories
          dirs: [
            // './hooks',
            // './composables' // Only root modules
            // './composables/**', // All nested modules
            // ...
          ],

          // Filepath to generate corresponding .d.ts file
          dts: `./auto-imports.d.ts`,

          // Disable auto import inside Vue template
          vueTemplate: false,

          // Custom resolvers, compatible with `unplugin-vue-components`
          resolvers: [
            /* ... */
          ],

          // Inject the imports at the end of other imports
          injectAtEnd: true,

          // Generate corresponding .eslintrc-auto-import.json file
          eslintrc: {
            enabled: true, // Default `false`
            filepath: `./.eslintrc-auto-import.json`, // Default `./.eslintrc-auto-import.json`
            globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
          },
        }),

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

unable to transfer Vuex store information to the graph

Currently, I am facing an issue with passing my vuex store data into my apexcharts graph. Despite my efforts, it seems like the data is not being displayed correctly. Can anyone provide guidance on what I might be doing wrong? My main objective is to updat ...

Rendering content on the server side and creating a cached version of the index.html file using Vuejs and Nodejs

Having multiple websites (site1.com, site2.com) connected to a single server poses an interesting challenge. I am able to capture the domain name when a user enters a site, and based on that domain name, I fetch appropriate JSON data from an API to display ...

Is there a Nuxt/Vue glitch causing the server to be called multiple times on a single route or page?

Why is Nuxt making multiple server calls on a single route/page? I tested the example from their express-template: import express from 'express' import { Nuxt, Builder } from 'nuxt' import api from './api' const app = expr ...

Encountering issues with npm installation on a Linux operating system

Embarking on a new journey learning Vue.js, I find myself in unchartered territory with Node.js. Initially, when I cloned the repository for my course and followed the setup instructions, everything ran smoothly without any issues. However, a blunder on my ...

The objects-to-csv module encountered an error: fs.existsSync is not a valid function for this

"TypeError: fs.existsSync is not a function" Whenever I try to create a CSV file and input some data into it, this error message pops up. const objectstocsv = require('objects-to-csv'); export default { data () { return { ...

Masked input fails to accurately capture data

When utilizing VueJS together with the Quasar framework. An issue arises when using a masked q-input, where the value becomes incorrect after a toggle. For instance, if we start with a default value of: officeNum: 654321, mobileNum: 12345678, Then our ...

How can I retrieve server-side data in the client-side using NodeJs (connecting to MySql) with Vue CRUD?

Currently, I am delving deeper into Vue and to make the learning process more engaging, I have established a connection to my MySql-DB using nodeJS. Following a detailed tutorial (), I successfully implemented a Login system. Now, my goal is to retrieve d ...

The system was unable to locate node.js with socket.io

I'm having trouble locating the file. According to the documentation I reviewed, socket.io is supposed to be automatically exposed. Encountered Error: polling-xhr.js?bd56:264 GET http://localhost:8081/socket.io/?EIO=3&transport=polling&t=LyY ...

Utilizing Vue.js to fetch information from a post API in Node.js

I'm currently working on developing a post API in Node.js, with Vue.js as my frontend framework and using vue-resource to interact with APIs. Here is the submit function I have implemented on the frontend: validateBeforeSubmit() { var self = this ...

Can Vue.js be paired with pure Node.js as a backend without relying on Express?

After successfully building a project with both vue js and node js, specifically with express, I'm curious if it's feasible to solely utilize node js without frameworks like express. ...

Vue-ctl project creation halted by operating system rejection

While working on a Vue-CLI project, I encountered an issue. Has anyone else faced this problem before? Operating system: Windows 10 - Command Prompt (admin rights) @vue-cli version: 4.5.4 npm version: 6.14.6 Here is the command I ran: vue create font_ ...

Having difficulty setting up a Vue app due to an error message indicating that an outdated version of NPM is being used, despite having already updated to the latest version

Details about my setup: I'm currently running Ubuntu 22.04.3 with Node Version: v18.18.2, NPM Version: 10.2.1, and Vue version: @vue/cli 5.0.8. To manage Node, I used NVM. Initially, the npm version was 9.x, so I updated it to 10.2.1. Following that ...

Leveraging Javascript Modules within a Typescript Vue Application

The issue at hand I've encountered a problem while attempting to integrate https://github.com/moonwave99/fretboard.js into my Vue project. My initial approach involved importing the module into a component as shown below: <template> <div&g ...

Guide on extracting data from MongoDB using VueJs

After successfully retrieving data from MongoDB using NodeJS, I am encountering an issue where the fields inside each object in the array are empty when trying to display them on my HTML page. The data is being fetched and displayed correctly in Chrome, bu ...

Can anyone help with displaying a PNG image in Vue/Node/Express? I am struggling to show the image that I sent from a Node.js server to a Vue app client

In my Node/Express application, I've set up a route like this: app.get('/get-image', function(req, res) { ... res.sendFile(path.join(__dirname, '..', account.profileImg)); }) Now in my client-side Vue app, I'm tryi ...

Transmitting data from express server to vue.js interface

Hey there, I am facing a bit of a complex situation and could really use some help. Here's what I've got: an application split into server-side using node/express and client-side with Vuejs. The issue arises when I try to create a user on the ba ...

Is it more advantageous to create two distinct projects for the frontend and backend along with an API, or should I consolidate them into a

Asking for some guidance on a few queries I have. I've developed a backend node server with express & mongo to run specific tasks and store them in the database, along with creating an admin page using express & bootstrap. Everything is functioning s ...

Where can Vue.js be found?

After dedicating an hour to watching instructional YouTube videos on Vue.js, I am still struggling to grasp the language! In the past, I have worked with Node.js, Jquery, and Mongodb to develop websites... I believe that web applications require multiple ...

Converting a string into an array of JSON objects

I am currently attempting to send data to my NodeJS server using the HTTP protocol (vue-resource). The goal is to send an array of JSON objects structured like this : [{"name":"Charlotte","surname":"Chacha","birth":"2000-04-02"},{"name":"Michael","surname ...

Utilizing Nicknames in a JavaScript Function

I'm dealing with a function that is responsible for constructing URLs using relative paths like ../../assets/images/content/recipe/. My goal is to replace the ../../assets/images section with a Vite alias, but I'm facing some challenges. Let me ...