Reputation: 1078
I have an input binding this:
v-model: user.settings.filter(item => item.id === 1)[0].value
The problem is that value is a string and it doesn't work. How can I convert to number?
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.
Upvotes: 1
Views: 8294
Reputation: 487
I agree with @Sumurai8, you shouldn't be receiving a type that needs to be mutated from front-end. Although here is an example on how you could do that, by using .map(Number)
new Vue({
el: "#app",
data: {
testNumber: undefined
},
computed: {
getTestNumber: function() {
return this.testNumber ? this.testNumber.split(',').map(Number) : null
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<h2>String to number:</h2>
<input type="text" v-model="testNumber">
<p v-html="getTestNumber"></p>
</div>
This converts a String of numbers to Numbers. As soon as you add a character it will return with NaN (not-a-number)
Upvotes: 0
Reputation: 20737
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.
Upvotes: 3