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 = storePlease 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>