Vue中选择select下拉框选项时调用函数的实现问题
解决Vue中Select下拉框Change事件调用函数失效的问题
首先咱们先修正你代码里的几个明显问题,再给出可行的解决方案:
原代码的问题分析
- 模板语法错误:你的
<option>标签里selected"多了一个引号,而且不能同时给两个选项设置selected属性,只能有一个默认选中项。 - methods里的逻辑错误:在Vue组件的
methods中,this指向的是组件实例,而不是<select>这个DOM元素,所以直接用this.options[this.selectedIndex]是拿不到下拉框选项的。
方案一:Vue数据驱动方式(推荐)
利用Vue的v-model绑定选中值,这是Vue推荐的做法,更符合数据驱动的思想:
模板代码
<select v-model="selectedPlatform" @change="login"> <option value="github" id="1" selected>Github</option> <option value="bitbucket" id="2">Bitbucket</option> </select>
组件脚本代码
export default { data() { return { selectedPlatform: 'github' // 和默认选中的选项value保持一致 } }, methods: { login() { // 直接根据绑定的选中值判断 if (this.selectedPlatform === 'github') { console.log("hi"); } else { console.log("hello"); } // 如果需要用到option的id,可以把选项定义成数组(更灵活) // const platformOptions = [ // { id: "1", value: "github", label: "Github" }, // { id: "2", value: "bitbucket", label: "Bitbucket" } // ] // const currentPlatform = platformOptions.find(item => item.value === this.selectedPlatform) // if (currentPlatform.id === "1") { // console.log("hi"); // } else { // console.log("hello"); // } } } }
方案二:通过事件对象获取DOM元素
如果你需要直接操作DOM元素,可以通过$event把事件对象传递给函数:
模板代码
<select @change="login($event)"> <option value="github" id="1" selected>Github</option> <option value="bitbucket" id="2">Bitbucket</option> </select>
组件脚本代码
export default { methods: { login(event) { // 通过事件对象获取到select元素,再拿到选中的option const selectElement = event.target; const selectedOption = selectElement.options[selectElement.selectedIndex]; if (selectedOption.id === "1") { console.log("hi"); } else { console.log("hello"); } } } }
内容的提问来源于stack exchange,提问作者Vishnupriya B
相关产品推荐
相关产品推荐

