Vue.js 绑定模型将字符串转换为数字 [英] Vue.js binding model convert string to number

查看:30
本文介绍了Vue.js 绑定模型将字符串转换为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入绑定:

v-model: user.settings.filter(item => item.id === 1)[0].value

问题是 value 是一个字符串,它不起作用.如何转换为数字?

The problem is that value is a string and it doesn't work. How can I convert to number?

user 变量是 vuex 的计算属性:

user variable is a computed property from vuex:

    computed: {
        ...mapGetters({
            user: 'auth/user',
        }),
    },

如果这个变量在数据中会很容易...但在计算属性中我不知道如何操作它.

If this variable was in data it would be easy... but in computed property I don't know how to manipulate it.

推荐答案

修复损坏的地方.这意味着如果您从某个地方的 api 获取 value,您必须修复该 api,以便它返回一个数字而不是一个字符串.如果您从某个地方的应用程序获取它,则需要将其保存为数字而不是字符串.如果在 Vuex getter 中动态计算,请使用 parseInt(..) (docs) 或 parseFloat(..) (docs) 将字符串中的任何内容解析为数字.但请记住,如果字符串中有无意义,则该属性中可能会出现 NaN.

Fix it where it is broken. That means if you get value from an api somewhere, you have to fix the api so that it returns a number and not a string. If you get it from the application somewhere, you need to save it as a number and not as a string. If it is calculated dynamically in the Vuex getter, use parseInt(..) (docs) or parseFloat(..) (docs) to parse whatever is in the string as a number. Keep in mind though that if you have nonsense in the string, you can end up with a NaN in that attribute.

这篇关于Vue.js 绑定模型将字符串转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆