Home > Blockchain >  Vue3 define ref as number without typescript
Vue3 define ref as number without typescript

Time:12-27

I have a vue2 component with composition API. In the script setup section I defined

const val = ref(1);
onMounted(() => {
  val.value = props.maxVal; //maxVal exists
  console.log(val.value)
//log gives value as number
});
const diff = computed(() => {
  return props.maxVal - val.value;

The last line gives the error Cannot convert object to primitive value. In the log it appears as if val.value is an integer as needed. What's wrong? How do I cast a ref in Vue3 without typescript correctly?

CodePudding user response:

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>

CodePudding user response:

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;
});
  • Related