Home > OS >  Input checbox v-model not checking with async data
Input checbox v-model not checking with async data

Time:07-06

I have a component that at the start of it, fetchs data from database. And it supose to check the input if the value is true or false. But the problem is that is not checking when its true. I tried :checked and it works, but i need the v-model because of the two way binding

code:

<input type="checkbox" v-model="data">


const data = ref(false)

onBeforeMount(async () => {
    await data = fetchingData()
})

I didnt write the hole code, because the code its on another computer, this was from head. But i am having poblems with v-model not checking. If i use :checked it works like a charm

Maybe this is a rookie mistake, but without using :checked with :change i am not seing any solution.

CodePudding user response:

I do not think it is the checkbox, but that you should use the .value when you write to a ref. Otherwise you loose the reactivity and v-model will not work.

onBeforeMount(async () => {
    data.value = await fetchingData()
})  

Hope this helps.

CodePudding user response:

You should use data.value instead of data for the reactivity. For the demo purpose I am directly assign the value as true. You can replace that with the API call code.

Live Demo :

<script type="module" src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.0.0-rc.5/vue.esm-browser.js"></script>
<div id="app">
  <input type="checkbox" v-model="data"/>
</div>

<script type="module">
import {ref, createApp, onBeforeMount } from 'https://cdnjs.cloudflare.com/ajax/libs/vue/3.0.0-rc.5/vue.esm-browser.js';

const app = createApp({
  setup() {
    let data = ref(false)
    onBeforeMount(() => {
      // data = true ❌
      data.value = true // ✅
    })
    return { data };
  }
});

app.mount('#app')
</script>

  • Related