简体   繁体   中英

How to configure checkbox input in Vue 3 to check/uncheck when clicking image

I am setting up a div container to include both an image and an input element with type checkbox . The checkbox input includes a click handler that passes a value as an argument to some function. The input also includes a :value binding, which is passed to an array called checkBoxArray . Finally, the input uses v-model=checkBoxArray to check when the array contains a value. If the array contains a value, then the checkbox will be checked. I also wish to enable clicking on an image next to the checkbox, in order to also check and uncheck the checkbox. However, simply adding the click handler to the image is not enough. How can I go about enabling a click handler on the image element to also check and uncheck a box?

Here is my code so far:

          <div v-for="item in items" :key="item.id">
            <span class="flex-1 flex">
              <span class="flex flex-col mr-4 mt-16">
                <input v-model="checkBoxArray" :value="item.id" @click="someFunction(item.id)" type="checkbox" class="h-5 w-5" />
              </span>
              <span class="flex flex-col">
                <img @click="someFunction(item.id)" class="h-full w-full" :src="item.image_url" alt="" />
              </span>
            </span>
          </div>

const checkBoxArray = ref([])

If I understood you correctly try like following snippet:

 const { ref } = Vue const app = Vue.createApp({ setup() { const checkBoxArray = ref([]) const items = [{id: 0, image_url: 'https://picsum.photos/50'}, {id: 1, image_url: 'https://picsum.photos/51'}] const someFunction = (id) => { checkBoxArray.value[id] = !checkBoxArray.value[id] console.log(id) } return { checkBoxArray, items, someFunction }; }, }) app.mount('#demo')
 <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script> <div id="demo"> <div v-for="item in items" :key="item.id"> <span class="flex-1 flex"> <span class="flex flex-col mr-4 mt-16"> <input v-model="checkBoxArray[item.id]" @click="someFunction(item.id)" type="checkbox" class="h-5 w-5" /> </span> <span class="flex flex-col"> <img @click="someFunction(item.id)" class="h-full w-full" :src="item.image_url" alt="" /> </span> </span> {{checkBoxArray}} </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM