一、普通遍历
1. 数组
<body>
<div id="first">
<ul>
<li v-for="movie in movies">{{movie}}li>
ul>
<ul>
<li v-for="(movie,index) in movies">{{index + 1}}.{{movie}}li>
ul>
div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js">script>
<script>
let module = new Vue({
el: '#first',
data: {
movies: ['雷神', '美队', '钢铁侠', '蚁人'],
},
})
script>
body>
2. 对象属性
<body>
<div id="first">
<ul>
<li>{{student.name}}li>
<li>{{student.address}}li>
<li>{{student.hobby}}li>
<li>{{student.age}}li>
ul>
<ul>
<li v-for="value in student">{{value}}li>
ul>
<ul>
<li v-for="(value_e,key_e) in student">{{key_e}}:{{value_e}}li>
ul>
<ul>
<li v-for="(value,key,index_e) in student">{{index_e + 1}}.{{key}}:{{value}}li>
ul>
div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
<script>
let module = new Vue({
el: '#first',
data: {
student: {
name: '舒展',
address: '陕西',
hobby: '游泳',
age: 20,
},
},
})
script>
body>
3. v-for 加key
- 一般v-for是用来遍历集合或者数组
- 官方建议,在使用v-for时候尽量为每个元素添加和元素对应的key
- key一般用对应的item,在向数组中间插值时,能够提高效率
<ul>
<li v-for="movie in movies" :key="movie">{{movie}}li>
ul>
二、数组方法
1. 即刻响应
- 数组的某些方法,调用函数修改后,会立刻相应渲染到页面上
- 可以在控制台或者直接修改源码
arr.push('aaa');
arr.push('aaa','bbb','ccc');
arr.unshift('aaa');
arr.unshift('aaa','bbb','ccc');
arr.pop();
arr.shift();
arr.sort();
arr.reverse();
<script>
let module = new Vue({
el: '#first',
data:{
movies:['雷神','美队','钢铁侠','蚁人'],
},
methods:{
firstOpe:function () {
this.movies.push('黑豹','蜘蛛侠');
}
}
})
script>
body>
2. 延迟响应
<body>
<div id="first">
<ul>
<li v-for="movie in movies">{{movie}}li>
ul>
<button @click=firstOpe()>add onebutton>
div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js">script>
<script>
let module = new Vue({
el: '#first',
data: {
movies: ['雷神', '美队', '钢铁侠', '蚁人'],
},
methods: {
firstOpe: function () {
this.movies[0] = '洛基';
console.log(this.movies);
}
}
})
script>
body>
三、可变参数方法
<body>
<div id="first">
{{firstFunction(10, 20)}}<br>
{{variableFunction(1, 2, 3, 4, 5, 6, 7, 7, 8, 9,)}}<br>
div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
<script>
let module = new Vue({
el: '#first',
methods: {
firstFunction(num1, num2) {
return num1 + num2;
},
variableFunction(...num) {
let result = 0;
for (let element of num) {
result += element;
}
return result;
},
}
})
script>
body>