Home > Mobile >  Vue 3 Typescript ComputedRef Issues
Vue 3 Typescript ComputedRef Issues

Time:12-02

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');
});

CodePudding user response:

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>

CodePudding user response:

if you want to create a computed property in typescript you will need to add a get infront of method.

get isAuthenticated () {
    return state.accessToken !== undefined
)

to make a type interface

interface recordTypes {
    pDate: Date;
}

Here is the full example

<template>
   
    <component
        v-if="componentName != ''"
        v-bind:is="componentName"
        v-on:updateConfirmationStatus="updateConfirmation"
    >
    </component>

   
</template>

<script lang="ts">
import { Vue, Options } from "vue-class-component";
import { useStore, ActionTypes } from "../store";
import Toaster from "../helpers/Toaster";
import { reactive } from "vue";
import PatientConsultationService from "../service/PatientConsultationService";
import Confirmation from "../components/Confirmation.vue";
import { required } from "@vuelidate/validators";
import useVuelidate from "@vuelidate/core";
import { camelCase } from "lodash";
import moment from "moment";

interface recordTypes {
    pDate: Date;
}

@Options({
    components: {
        Confirmation
    }
})
export default class Assessments extends Vue {
    private recordList: recordTypes[] = [];
    private recordID = 0;
    private pService;
    private isCollapsed = true;
    private submitted = false;
    private toast;
    private componentName = "";
    private vuexStore = useStore();

    private state = reactive({
        weight: 0,
        height: 0,
        o2: 0,
        respiration: 0,
        temperature: 0,
        pressure: 0,
        pulse: 0
    });

    private validationRules = {
        weight: {
            required
        },
        height: {
            required
        },
        o2: {
            required
        },
        respiration: {
            required
        },
        temperature: {
            required
        },
        pressure: {
            required
        },
        pulse: {
            required
        }
    };

    private v$ = useVuelidate(this.validationRules, this.state);

    created() {
        this.pService = new PatientConsultationService();
        this.toast = new Toaster();
    }

    mounted() {
        this.loadList();
    }

    get patientID() {
        return this.vuexStore.getters.getReceiptID;
    }

    saveItem(isFormValid) {
        this.submitted = true;
        if (isFormValid) {
            this.pService
                .saveAssessment(this.state, this.patientID)
                .then(res => {
                    this.clearItems();
                    this.toast.handleResponse(res);
                    this.loadList();
                });
        }
    }

    clearItems() {
        this.state.weight = 0;
        this.state.height = 0;
        this.state.o2 = 0;
        this.state.respiration = 0;
        this.state.temperature = 0;
        this.state.pressure = 0;
        this.state.pulse = 0;
    }

    loadList() {
        this.pService.getAssessment(this.patientID).then(data => {
            const res = this.camelizeKeys(data);
            this.recordList = res.records;
        });
    }

    camelizeKeys = obj => {
        if (Array.isArray(obj)) {
            return obj.map(v => this.camelizeKeys(v));
        } else if (obj !== null && obj.constructor === Object) {
            return Object.keys(obj).reduce(
                (result, key) => ({
                    ...result,
                    [camelCase(key)]: this.camelizeKeys(obj[key])
                }),
                {}
            );
        }
        return obj;
    };

    get sortedRecords() {
        let sortedList = {};

        this.recordList.forEach(e => {
            const date = String(e.pDate);
            if (sortedList[date]) {
                sortedList[date].push(e);
            } else {
                sortedList[date] = [e];
            }
        });

        return sortedList;
    }

    formatDate(d) {
        const t = moment().format("YYYY-MM-DD");
        let fd = "";

        if (d == t) {
            fd = "Today "   moment(new Date(d)).format("DD-MMM-YYYY");
            this.isCollapsed = false;
        } else {
            fd = moment(new Date(d)).format("DD-MMM-YYYY");
            this.isCollapsed = true;
        }

        return fd;
    }

    deleteItem(id) {
        this.vuexStore.dispatch(
            ActionTypes.GET_RECEIPT_TITLE,
            "Are you sure to delete this"
        );
        this.componentName = "Confirmation";
        this.recordID = id;
    }

    updateConfirmation(b) {
        this.componentName = "";
        if (b.result) {
            this.pService.deleteAssessment(this.recordID).then(res => {
                this.toast.handleResponse(res);
                this.loadList();
            });
        }
    }
}
</script>
  • Related