0
点赞
收藏
分享

微信扫一扫

Vue--解决Expected Number with value 123, got String with value “123“.

Ad大成 2022-02-15 阅读 195


简介

        本文用示例介绍Vue开发中的一个常见的警告的方法。

        警告信息为:[Vue warn]: Invalid prop: type check failed for prop "age". Expected Number with value 123, got String with value "123".

        警告的含义:无效的属性:age属性类型检查失败。期望是一个值为123的Number,但接收到的是值为“123”的String。

问题复现

用一个组件(Parent.vue)调用另一个组件(Child.vue),子组件(Child.vue)对props进行类型的设置。

代码

Parent.vue(父组件)

<template>
<div class="outer">
<h3>父组件</h3>

名字:<input v-model="name">
年龄:<input v-model="age">

<child :name="name" :age="age"></child>
</div>
</template>

<script>
import Child from "./Child";
export default {
name: 'Parent',
components: {Child},
data() {
return {
name: 'Tony',
age: 20
}
}
}
</script>

<style scoped>
.outer {
margin: 20px;
border: 2px solid red;
padding: 20px;
}
</style>

Child.vue(子组件) 

<template>
<div class="outer">
<h3>子组件</h3>
<div>获得顶层组件的name:{{name}}</div>
<div>获得顶层组件的age:{{age}}</div>
</div>
</template>

<script>
export default {
props: {
name: {
type: String
},
age: {
type: Number
}
}
}
</script>

<style scoped>
.outer {
margin: 20px;
border: 2px solid blue;
padding: 20px;
}
</style>

路由(store/index.js)

import Vue from 'vue'
import Router from 'vue-router'
import Parent from "../components/Parent";

Vue.use(Router)

export default new Router({
routes: [
{
path: '/parent',
name: 'Parent',
component: Parent,
}
],
})

测试

测试1:访问

访问:​​http://localhost:8080/#/parent​​

Vue--解决Expected Number with value 123, got String with value “123“._javascript

测试2:修改值

可以发现:

子组件将props的name的type指定为String类型,输入时不会报警告。

子组件将props的age的type指定为Number类型,输入时会报警告。

原因分析

<input v-model="age">

这样获取的输入值的类型为String类型,而子组件要求是Number类型,所以会报警告。

问题解决

将<input>标签获取的值指定为Number类型。官网:​​表单输入绑定 — Vue.js​​

方法是:给 v-model 添加 number 修饰符:

<input v-model.number="age" type="number">

解决后的示例

只修改Parent.vue(父组件):

<template>
<div class="outer">
<h3>父组件</h3>

名字:<input v-model="name">
年龄:<input v-model.number="age" type="number">

<child :name="name" :age="age"></child>
</div>
</template>

<script>
import Child from "./Child";
export default {
name: 'Parent',
components: {Child},
data() {
return {
name: 'Tony',
age: 20
}
}
}
</script>

<style scoped>
.outer {
margin: 20px;
border: 2px solid red;
padding: 20px;
}
</style>

测试:


举报

相关推荐

0 条评论