简体   繁体   English

Vue3 将 ref 定义为没有 typescript 的数字

[英]Vue3 define ref as number without typescript

I have a vue2 component with composition API. In the script setup section I defined我有一个组成为 API 的 vue2 组件。在我定义的脚本设置部分

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 .最后一行给出错误Cannot convert object to primitive value In the log it appears as if val.value is an integer as needed.在日志中,根据需要,val.value 似乎是 integer。 What's wrong?怎么了? How do I cast a ref in Vue3 without typescript correctly?如何在没有 typescript 的情况下正确地在 Vue3 中投射一个 ref?

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如果您在computed()方法/属性中遇到异常,那么我认为您需要使用parseInt() or parseFloat() ie 将val.value为整数/浮点数

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:如果仍然遇到错误,则调试props.maxVal并尝试查找它是数字还是 object。如果是数字,请尝试以下代码段:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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