简体   繁体   English

如何在 Vue 3 中配置复选框输入以在单击图像时选中/取消选中

[英]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 .我正在设置一个 div 容器以包含图像和类型为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 .输入还包括一个 :value 绑定,它被传递给一个名为checkBoxArray的数组。 Finally, the input uses v-model=checkBoxArray to check when the array contains a value.最后,输入使用v-model=checkBoxArray来检查数组何时包含值。 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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