Home > Software engineering >  Vue.js3 Passing value from function to label for checkbox input, and have label change based upon th
Vue.js3 Passing value from function to label for checkbox input, and have label change based upon th

Time:05-03

<template>
    <div>
        <input @change="change($event)"  type="checkbox" id="check" v-model="checked"  />
        <label for="check" >{{ status }}</label>
    </div>

</template>

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

         interface Props {
            status?: string
        }

        const props = withDefaults(defineProps<Props>(), {
            status: "Locked",
        });

        const checked = ref(false)
        let status = "";

        const change = () => {
            
             if(checked.value === true) {
                    status="Locked"
                } else {
                    status="Unlocked"
                }
                console.log(checked.value, status)
        }
</script>

(Using the composition api w/setup) The console.log(checked.value, status) returns the correct information, I just can't figure out how to use status as the label, and have it change when the checkbox is clicked.

Desired action would be:

  • checked.value = true; status = "Unlocked" <--to be displayed as label

  • checked.value = false; status="Locked" <--to be displayed as label

Any suggestions would be appreciated.

CodePudding user response:

status should be also a reactive variable:

const status = ref("");

and re-assign the content via

status.value = 'locked';

keep in mind, that every variable you want to display in your template, has to be reactive.

  • Related