search

Home  >  Q&A  >  body text

Reducing boilerplate code in the Vue 3 Composition API: simplifying router and storage implementation

<p>Using Vue 3’s Composition API, each view needs the following code: </p> <pre class="brush:js;toolbar:false;">import { useRouter, useRoute } from 'vue-router' import { useStore } from 'vuex' export default { setup() { const router = useRouter() const store = useStore() // ... } } </pre> <p>Is there a way to declare them once when creating the application and then pass them to the created application and simply use them in the application view without requiring these declarations? In vue2, these are passed when the application is initialized, and then <code>this.$store</code> / <code>this.$router</code> will work fine. </p> <p>An idea to use global variables, which can easily cause problems: in <code>app.vue</code> you can declare them once like this: </p> <pre class="brush:js;toolbar:false;">import { useStore } from 'vuex' export default { setup() { globalthis.store = useStore() </pre> <p>Then <code>store</code> will be available everywhere. </p>
P粉281089485P粉281089485459 days ago481

reply all(1)I'll reply

  • P粉436052364

    P粉4360523642023-08-30 14:44:15

    In setup(), the component instance is not available because the component has not been created yet, so there is no this context in the Composition API to use this.$store.

    I think the only way to make store/router variables available in setup() without requiring additional imports is to attach them as global variables to the window/globalThis (ignoring restrictions on 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
    

    Please note that in the Options API and templates, you can still use

    $store and $router to access the store and router. For specific examples, please refer to Options API## Example in template , for Vuex 4 and Vue Router 4:

    <template>
      <div>{{ $store.state.myProp }}</div>
      <button @click="$router.back()">返回</button>
    </template>
    
    <script>
    export default {
      mounted() {
        console.log(this.$store.state.myProp)
        console.log(this.$router.currentRoute)
      }
    }
    </script>
    

    reply
    0
  • Cancelreply