How to compare two strings in VueJS?

Hi Friends đź‘‹,

Welcome To SortoutCode! ❤️

To compare the string in VueJS, we are using The directive v-if used to conditionally render a block. The block will only be rendered if the directive’s expression returns a truth value.

Today I am going to show you How do you compare two strings in VueJS.

Table of contains

  • Define sitename,siteurl property for Test
  • Using the v-if directive

Let’s start today’s tutorial How do I compare two string in VueJS?

Define sitename,siteurl property for Test

Let’s define the sitename,siteurl in the data of the FirstComponent.vue component for testing purposes.

FirstComponent.vue

<script>
export default {
    name: 'FirstComponent',
    data(){
        return{
            sitename:"SortoutCode", 
            siteurl:"https://sortoutcode.com/"
        }
    },
}
</script>

Data is used to define properties in a particular component. In a single-file component, data() is a function that returns a set of properties that have been defined in the function.

we define the three properties that are sitename,siteurl.

Using the v-if directive

we are using the v-if directive to conditionally render the block. The block will only render if the directive’s expression returns a true value.

FirstComponent.vue

<template>
    <div>
        <span v-if="sitename == 'SortoutCode'">SortoutCode</span>
        <p v-if="siteurl == 'https://sortoutcode.com/'">https://sortoutcode.com/</p>
        <span v-if="sitename == 'website'">SortoutCode</span>
    </div>
</template>
<script>
export default {
    name: 'FirstComponent',
    data(){
        return{
            sitename:"SortoutCode", 
            siteurl:"https://sortoutcode.com/"
        }
    },
}
</script>

As you can see the output’s first two blocks are rendered because its expression value returns the true value. And the last expression value returns the false that’s why it does not render the last one block.

For now, let’s check the output.

Output

v-if directive

All the best đź‘Ť.

Follow me on Twitter