Vue中如何在select的change事件中额外传递cat_id等自定义数据
解决方案
方式1:事件绑定时直接追加自定义参数(推荐,通用性更强)
你可以在@change绑定方法时,除了默认的事件对象$event外,直接把需要额外传递的cat_id作为第二个参数传入:
修改后模板代码:
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <li>Category ID: {{ cat_id }}</li> <li style="list-style: none;"> <select style="width: auto;" @change="testChange($event, cat_id)"> <option selected disabled>Options</option> <option v-for="date in testing_dates" :value="date">{{ date }}</option> </select> </li> </div>
修改后方法代码:
var vm = new Vue({ el: "#app", props: { }, data: { testing_dates:['2021-11-29', '2021-11-30'], cat_id: [123] }, methods: { testChange(event, catId){ // 拿到选中的日期 const selectedDate = event.target.value // 构造你需要的关联对象 const result = { cat_id: catId, selected_date: selectedDate } console.log(result) }, }, });
这种方式通用性最强,哪怕你后续要传v-for循环里的项、其他自定义变量,都可以用同样的方式追加参数即可。
方式2:直接在方法内读取实例属性
因为cat_id是你当前Vue实例的data属性,你完全不需要额外传参,直接在方法内通过this.cat_id就能读取到值,不用修改模板的事件绑定逻辑:
methods: { testChange(event){ const selectedDate = event.target.value const result = { cat_id: this.cat_id, selected_date: selectedDate } console.log(result) }, }
这种方式更简洁,适合需要读取的自定义数据本身就是当前实例属性的场景。
内容的提问来源于stack exchange,提问作者Geoff_S
相关产品推荐
相关产品推荐

