Issue
I stumbled across some issues with Typescript and Vue3. I guess I am using Typescript wrong here.
I created myself a store with Vue's Composition API.
import {computed, reactive} from "vue";
const state = reactive({
accessToken: undefined,
user: {},
})
const isAuthenticated = computed(() => {
return state.accessToken !== undefined
})
export default {
state: readonly(state),
isAuthenticated
}
Written a type / interface for it:
import {ComputedRef} from "vue";
export interface UserStore{
state: Readonly<any>;
isAuthenticated: ComputedRef<boolean>;
}
But when I now want to make use of it in my vue component.
Like this for example:
<h1 v-if="userStore.isAuthenticated">is true</h1>
It returns true even if it is obviously false.
I inject the store via inject:
setup(){
return {
userStore: inject('userStore') as UserStore
}
}
A similar issue occurs when I want to return a computed() string. It is wrapped within quotation marks when I use it in a template.
What's the issue here?
#edit I provide the UserStore in main.ts
/* Stores */
import UserStore from './store/user-store'
const app = createApp(App)
.use(IonicVue, {
mode: 'ios'
})
.use(router)
.provide('userStore',UserStore);
router.isReady().then(() => {
app.mount('#app');
});
Solution
A ref is an object, so userStore.isAuthenticated
expression is always truthy.
Refs (incuding computed) are automatically unwrapped in a template when they are returned from setup function. It should be:
const userStore = inject('userStore') as UserStore
const { isAuthenticated } = userStore;
return {
isAuthenticated
}
Otherwise a ref needs to be unwrapped manually:
<h1 v-if="userStore.isAuthenticated.value">is true</h1>
Answered By - Estus Flask
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.