Reducing boilerplate code in the Vue 3 Composition API: simplifying router and storage implementation
P粉281089485
P粉281089485 2023-08-29 18:19:32
0
1
485
<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粉281089485
P粉281089485

reply all(1)
P粉436052364

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>

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template