【发布时间】:2020-09-05 04:52:39
【问题描述】:
考虑以下组合函数:
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,
}
}
现在当我想在/router/index.js 中使用isAuthenticated 计算属性时,Vue 会抛出错误“未捕获的错误:[vue-composition-api] 必须在使用前调用 Vue.use(plugin)任何功能。”:
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
})
组件 API 由文件 '/boot/auth.js' 中的 Quasar Framework boot file 实例化:
import VueCompositionApi from '@vue/composition-api'
import { boot } from 'quasar/wrappers'
export default boot(({ Vue }) => {
Vue.use(VueCompositionApi)
})
有没有办法在组件之外使用导出的计算属性?
根据this example,这是一个使用相同组合API的库,当isAuthenticated在Router对象中被实例化时,它应该可以工作。有more people 在为此苦苦挣扎,但我似乎无法正确处理。
【问题讨论】:
标签: vue.js vuejs3 vue-composition-api