简体   繁体   中英

Vue3 define ref as number without typescript

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?

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>

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM