Home > Enterprise >  How to toggle two tags with Vue and Typescript?
How to toggle two tags with Vue and Typescript?

Time:06-22

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 >
                <div>
                    <h1 >Lorem, ipsum.</h1>
                    <p >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>

CodePudding user response:

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 >
                <div>
                    <h1 >Lorem, ipsum.</h1>
                    <p >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>
  • Related