简体   繁体   English

Vue.js + 获取 ul 的选定 li 项

[英]Vue.js + get selected li item of ul

I have a list displayed like a dropdown -我有一个像下拉列表一样显示的列表-

Each of the items except 'Create New Filter' is bound to a key so i can uniquely identify the li items.除了“创建新过滤器”之外的每个项目都绑定到一个键,因此我可以唯一地识别 li 项目。

I want to know how can i get the selected li item on save and do operations accordingly我想知道如何在保存时获取选定的 li 项目并进行相应的操作

What would be the good approach for this so i can understand when 'Create new filter' is clicked or when other li items are selected什么是好的方法,所以我可以理解何时单击“创建新过滤器”或选择其他 li 项目

在此处输入图像描述

Below is the code -下面是代码 -

 <ul>
     <li v-on:click="create">Create New</li>
     <li v-for="item in list" :key="item.id" v-on:click="Change(item.id,item.text)">{{ item.text }}</li>
</ul>

As per my understanding this approach is not good, I am not sure why you are building dropdown by using <ul> and <li> instead of select element as it is a form element and provide a better way to get the selected option value by the help of v-model directive.根据我的理解,这种方法不好,我不确定您为什么要使用<ul><li>而不是select元素来构建下拉菜单,因为它是一个表单元素,并提供了一种更好的方法来获取选定的选项值v-model指令的帮助。

Anyhow I worked as per your requirement and came up with the solution.无论如何,我按照您的要求工作并提出了解决方案。

 var app = new Vue({ el: '.dropdown', data: { list: [{ id: 1, text: 'First Filter' }, { id: 2, text: 'First Filter 2021' }, { id: 3, text: 'Full Filter' }], selectedListItem: null }, methods: { create() { console.log('New filter Create Called'); }, getSelected (item) { this.selectedListItem = item; }, save() { if (this.selectedListItem) { console.log(this.selectedListItem); } else { console.log('No list option selected'); } } } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <div class="dropdown"> <input type="text" placeholder="Select Filter" class="dropdown-toggle" data-toggle="dropdown"/> <ul class="dropdown-menu"> <li v-on:click="create">Create New</li> <li v-for="item in list" :key="item.id" v-on:click="getSelected(item)">{{ item.text }}</li> </ul> <button @click="save">SAVE</button> </div>

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

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