vue接收索引_vue.js指令v-for使用及索引获取

本文介绍了Vue.js中v-for指令的使用,包括如何遍历数组和对象,以及如何在v-for块内获取当前元素的索引。通过示例展示了在模板中直接使用$index获取索引,以及在点击事件中如何获取和利用索引值。此外,还提到了通过自定义属性或直接传递索引到方法中来实现索引的获取。最后,文章提到了这些内容已收录至《Vue.js前端组件学习教程》。
摘要由CSDN通过智能技术生成

1.v-for

直接上代码。

示例一:

  • {{ tab.text }}

new Vue({

el: '#didi-navigator',

data: {

tabs: [

{ text: '巴士' },

{ text: '快车' },

{ text: '专车' },

{ text: '顺风车' },

{ text: '出租车' },

{ text: '代驾' }

]

}

})

2.索引

在 v-for 块内我们能完全访问父组件作用域内的属性,另有一个特殊变量 $index,正如你猜到的,它是当前数组元素的索引:

  • {{ parentMessage }} - {{ $index }} - {{ item.message }}

var example2 = new Vue({

el: '#example-2',

data: {

parentMessage: 'Parent',

items: [

{ message: 'Foo' },

{ message: 'Bar' }

]

}

})

另外,你可以为索引指定一个别名(如果 v-for 用于一个对象,则可以为对象的键指定一个别名):

{{ index }} {{ item.message }}

从 1.0.17 开始可以使用 of 分隔符,更接近 JavaScript 遍历器语法:

示例二:

  • Text:{{option.text}}--Vlue:{{option.value}}

你点击的索引为: {{ click }}

试着点击上方LI条目

new Vue({

el: 'body',

data: {

click: 'a',

options: [

{ text: '上海市', value: '20' },

{ text: '湖北省', value: '43' },

{ text: '河南省', value: '45' },

{ text: '北京市', value: '10' }

]

},

methods:{

getIndex:function($index){

this.click=$index;

}

}

});

3.在点击事件中取到索引

方法一:添加自定义属性

示例三:

a{display: block;}

new Vue({

el: 'body',

data: {

items: [

{ text: '巴士' },

{ text: '快车' },

{ text: '专车' },

{ text: '顺风车' },

{ text: '出租车' },

{ text: '代驾' }

]

},

methods: {

onclick:function(event){

event.preventDefault();

let target = event.target

console.log(target.getAttribute("data-index"));

document.getElementById('index').value = target.getAttribute("data-index");

}

}

})

方法二:直接传入索引值

示例四(和二差不多):

a{display: block;}

new Vue({

el: 'body',

data: {

items: [

{ text: '巴士' },

{ text: '快车' },

{ text: '专车' },

{ text: '顺风车' },

{ text: '出租车' },

{ text: '代驾' }

]

},

methods: {

onclick:function(index){

// index.preventDefault();

console.log(index);

document.getElementById('index').value = index;

}

}

})

效果与方法一相同。

如果想直接传索引可以用以下方法:

示例五:

a{display: block;}

{{ item.text }}

new Vue({

el: 'body',

data: {

items: [

{ text: '巴士' },

{ text: '快车' },

{ text: '专车' },

{ text: '顺风车' },

{ text: '出租车' },

{ text: '代驾' }

]

},

methods: {

onclick:function(index){

// index.preventDefault();

console.log(index);

document.getElementById('index').value = index;

window.location.href = "http://www.baidu.com";

}

}

})

本文已被整理到了《Vue.js前端组件学习教程》,欢迎大家学习阅读。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值