Consider the following composition function:
import { computed, ref } from '@vue/composition-api'
import { isInternetExplorer } from 'src/services/utils/utilsService'
import { Screen } from 'quasar'
import { auth, getAllScopes } from 'src/services/auth/authService'
const isLoginPopup = Screen.lt.sm || isInternetExplorer ? false : true
const accountID = ref('')
export const setAccountID = () => {
const account = auth.getAccount()
if (account) { accountID.value = account.idTokenClaims.oid }
else { accountID.value = '' }
}
export const useAccount = () => {
const loading = ref(false)
const disabled = ref(false)
const login = async () => {
loading.value = true
disabled.value = true
const allScopes = getAllScopes()
if (isLoginPopup) {
try {
await auth.loginPopup(allScopes)
} finally {
setAccountID()
disabled.value = false
loading.value = false
}
} else {
auth.loginRedirect(allScopes)
}
}
const logout = () => { auth.logout() }
return {
accountID: computed(() => accountID.value),
isAuthenticated: computed(() => Boolean(accountID.value)),
loading: computed(() => loading.value),
disabled: computed(() => disabled.value),
login, logout,
}
}
Now when I want to use the isAuthenticated
computed property within /router/index.js
Vue throws the error "Uncaught Error: [vue-composition-api] must call Vue.use(plugin) before using any function.":
import { route } from 'quasar/wrappers'
import VueRouter from 'vue-router'
import routes from './routes'
import { useAccount } from 'src/comp-functions/useAccount'
export default route(function ({ Vue }) {
Vue.use(VueRouter)
const Router = new VueRouter({
scrollBehavior: () => ({ x: 0, y: 0 }),
routes,
mode: process.env.VUE_ROUTER_MODE,
base: process.env.VUE_ROUTER_BASE,
})
Router.beforeEach((to, from, next) => {
const { isAuthenticated } = useAccount()
if (isAuthenticated || to.path === '/' || to.path === '/login') {
next()
} else {
next('/login')
}
})
return Router
})
The component API is instantiated by a Quasar Framework boot file in the file '/boot/auth.js':
import VueCompositionApi from '@vue/composition-api'
import { boot } from 'quasar/wrappers'
export default boot(({ Vue }) => {
Vue.use(VueCompositionApi)
})
Is there a way to use an exported computed property outside of a component?
According to this example, which is a library using the same composition API, it should work when isAuthenticated
is instantiated within the Router
object. There are more people struggling with this but I can't seem to get it right.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…