[Vuejs]-Vue3 define ref as number without typescript

0👍

This code example work normaly

<template>
  <div>diff : {{ diff }}</div>
</template>

<script>
import {
  createComponent,
  computed,
  onMounted,
  ref,
} from "@vue/composition-api";

export default createComponent({
  name: "CompositionCounter",
  props: {
    maxVal: {
      type: Number,
      default: 15,
    },
  },
  setup(props) {
    const val = ref(1);
    onMounted(() => {
      val.value = props.maxVal - 10; //maxVal exists
      console.log(val.value);
      //log gives value as number
    });
    const diff = computed(() => {
      return props.maxVal - val.value;
    });

    return {
      diff,
    };
  },
});
</script>

0👍

If you got exception in computed() method/property then I think you need to cast val.value to integer/float using parseInt() or parseFloat() i.e.

const diff = computed(() => {
  return props.maxVal - parseInt(val.value);
});

If still face error then debug props.maxVal and try to find, is it number or object. In case it’s a number then, try following snippet:

const diff = computed(() => {
  let evaluatedValue = parseInt(props.maxVal) - parseInt(val.value);
  props.maxVal = evaluatedValue;
  return evaluatedValue;
});

Leave a comment