Home >Web Front-end >Front-end Q&A >How to implement the function of clicking to select a product list in vue
Recently I was working on an e-commerce website and needed to implement the function of clicking to select a product list. I took this opportunity to learn the Vue framework.
In Vue, it is very simple to click on the selected list. You only need to use the v-on instruction and v-bind instruction provided by Vue.
First, define a product list in the template, with a checkbox behind each product.
<ul> <li v-for="item in itemList"> <input type="checkbox" v-bind:id="item.id" v-model="item.checked"/> <label v-bind:for="item.id">{{item.name}}</label> </li> </ul>
The v-for instruction here is a loop instruction in Vue, which is used to traverse each element in the itemList array. The v-bind directive is an attribute binding directive in Vue, which can bind data in Vue to HTML elements. The v-model directive is a two-way binding directive in Vue, which can achieve two-way synchronization of data.
In data, declare the itemList array and initialize the id, name and checked attributes of each element.
data() { return { itemList: [ { id: 'item1', name: '商品1', checked: false }, { id: 'item2', name: '商品2', checked: false }, { id: 'item3', name: '商品3', checked: false } ] } }
When the user clicks on the checkbox, the click event will be triggered. We only need to define a toggleCheck method in methods to invert the status of the currently selected checkbox.
methods: { toggleCheck(item) { item.checked = !item.checked; } }
Finally, use the v-on directive in the template to bind the click event and call the toggleCheck method.
<input type="checkbox" v-bind:id="item.id" v-model="item.checked" v-on:click="toggleCheck(item)"/>
In this way, the function of clicking on the selected list can be realized.
To summarize, Vue is very simple to implement a click-to-select list. You only need to use the v-for, v-bind, v-model and v-on instructions provided by Vue to bind the data in HTML and Vue. Defined, two-way synchronization of data and binding of events can be achieved. The Vue framework is not only low-cost to learn, but also very suitable for developing small and medium-sized projects. If you also want to improve your front-end skills, you might as well learn the Vue framework!
The above is the detailed content of How to implement the function of clicking to select a product list in vue. For more information, please follow other related articles on the PHP Chinese website!