Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to toggle two tags with Vue and Typescript?

Hi I’m new with Typescript. I’ve toggled two tags multiple times just in Vue, but now for the first time I’m doing it with Typescript.

In console log i see changes (true <–> false), but p tag is always the same.

<script lang="ts">
export default defineComponent({
    inheritAttrs: false,
})
</script>

<script lang="ts" setup>
let checked = false
function checkFunction(value: any) {
    checked = !checked
}
</script>

<template>
    <div>
        <button @click="checkFunction">
            <div class=" w-2/6 mx-auto  my-auto flex justify-between">
                <div>
                    <h1 class="text-md font-medium text-black ">Lorem, ipsum.</h1>
                    <p class="text-md font-medium text-gray-500 ">Lorem ipsum dolor sit amet consectetur.</p>
                </div>

               <p v-if="checked === true">This is true</p>
               <p v-else-if="checked === false">This is false </p>

           </div>
       </button>
   </div>
</template>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should define the checked as reactive variable using ref, and use .value field to mutate it :


<script lang="ts">


export default defineComponent({
    inheritAttrs: false,
})
</script>

<script lang="ts" setup>
import {ref} from 'vue'

let checked = ref(false)

function checkFunction(value: any) {
    checked.value = !checked.value
}
</script>

<template>
    <div>
        <button @click="checkFunction">
            <div class=" w-2/6 mx-auto  my-auto flex justify-between">
                <div>
                    <h1 class="text-md font-medium text-black ">Lorem, ipsum.</h1>
                    <p class="text-md font-medium text-gray-500 ">Lorem ipsum dolor sit amet consectetur.</p>
                </div>

               <p v-if="checked">This is true</p>
               <p v-else>This is false </p>

           </div>
       </button>
   </div>
</template>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading