Vue3将ref定义为编号,无 typescript

x33g5p2x  于 2022-12-27  发布在  Vue.js
关注(0)|答案(2)|浏览(182)

我有一个带有合成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;

最后一行给出了错误Cannot convert object to primitive value。在日志中,它看起来好像瓦尔.value是一个需要的整数。出了什么问题?如果没有正确的打字脚本,我如何在Vue3中强制转换一个ref?

cnh2zyt3

cnh2zyt31#

此代码示例工作正常

<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>
3b6akqbq

3b6akqbq2#

如果您在computed()方法/属性中遇到异常,那么我认为您需要使用parseInt() or parseFloat()val.value转换为整型/浮点型,即

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

如果仍然面临错误,然后调试props.maxVal,并尝试找到,它是一个数字或对象。如果它是一个数字,然后,尝试以下代码片段:

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

相关问题