Recently, I have been exploring the idea of defining ref() or computed values in an external class to improve code structure and reduce clutter in .vue files.
For instance, consider a test.ts file like the one below:
import { ref, computed } from "vue";
import type { Ref, ComputedRef } from "vue";
export class Test {
public refValue: Ref<number> = ref(0)
public compValue: ComputedRef<string> = computed(() => {
if (this.refValue.value === 0) return 'No Value given'
else return `Value is ${this.refValue.value}`
})
constructor() {}
public init() {
this.refValue.value = 10
}
}
And a Test.vue file structured as follows:
<template>
<div v-if="test">
<span>{{ test.refValue }}</span>
<span>{{ test.compValue }}</span>
</div>
<template>
<script setup lang="ts">
import { Test } from './Test.ts'
import { onMounted } from 'vue'
const test = ref<Test | null>(null)
onMounted(() => {
test.value = new Test()
test.value.init()
})
</script>
I attempted to implement this example, but encountered issues where the .ts file was overwriting the assigned ref() value for refValue. Consequently, when initializing at init(), a Type error occurred because there is no 'value' associated with 0.
This led me to the question: Is it feasible to approach it this way, and if so, what mistakes might I be making?
( Source : VueJS.org )