Reducing boilerplate code in the Vue 3 Composition API: simplifying router and storage implementation
P粉281089485
2023-08-29 18:19:32
<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>
In
setup()
, the component instance is not available because the component has not been created yet, so there is nothis
context in the Composition API to usethis.$store
.I think the only way to make store/router variables available in
Please note that in the Options API and templates, you can still usesetup()
without requiring additional imports is to attach them as global variables to the window/
globalThis(ignoring restrictions on global variables):
$store
and
$routerto access the store and router. For specific examples, please refer to
Options API## Example in template , for Vuex 4 and Vue Router 4: