How do we change string according to computed property's condition


#1

i have computed properties in vue file like result1, result2, …result20 . They are numbers and constantly changing , i want to add text after them if result1 is positive “profit” if negative “loss” .
how should i check this results are positive or negative, dont know how to use JS commands like Math.sign(result1) inside VUE files or do i need them.


#2

Hello. Can you provide more context? What constitutes a loss or a profit? Is it the delta between the last-known balance of a result? Or is it as simple as being above or below zero?

Please provide a code snippet as well, and make it as generic as possible in order to avoid sharing any proprietary information from your company.


#3

Data is coming from a restapi with axios, computed proterties calculates some basic math on them and result is stored in result props , some of that calculations becomes below zero so if it becomes negative i will show them with red color and loss text to target.trying to figure out if result1 is below zero how do i code it at vue


#4

#5

How about a simple:

 <span :style="{color: result1<0 ? 'red' : '' }">
    {{result1}}{{result1>0 ? ' profit' : (result1<0 ? ' loss' : '')}}
 </span>

Or to save repetition you could use a filter or method:

// html
<span :style="lossColor(result1)">{{profitOrLoss(result1)}}</span>

// js
export default {
    methods: {
        lossColor: function(value) {
            return value<0 ? {color: 'red'} : {};
        },
        profitOrLoss: function(value) {
            return value + (value>0 ? ' profit' : (value<0 ? ' loss' : ''));
        }
    },
}

Also, ideally, instead of having hard-coded computed properties result1, result2, etc, etc, you should be storing these in an array and display them all using v-for:

<span v-for="result in results" :style="{color: result<0 ? 'red' : '' }">
    {{result}}{{result>0 ? ' profit' : (result<0 ? ' loss' : '')}}
</span>