vue指令2

129 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第6天,点击查看活动详情

前言:指令是带有v-前缀的特殊属性,其值限定为单个表达式。指令的作用是,当表达式得值发现变化,将其产生的连带影响应用到DOM上 点击查看上篇vue指令1

v-for

v-for指令就是通过循环的方式来渲染一个列表,循环的对象可以是数组,也可以是一个JavaScript对象

v-for遍历数组

表达式的语法形式为item in items,其中items是源数据数组,item则是被迭代的数组元素的别名。

演示代码

<template>
  <div id="app">
    <ul>
      <li v-for="num in nums">{{num.title}}</li>
    </ul>
    <router-view />
  </div>
</template>
<script>
export default {
  name: 'App',
  data() {
    return {
      nums: [{ title: '1' }, { title: '2' }, { title: '3' }]
    }
  }
}
</script>

运行结果:

image.png vue实例的数据对象中定义了一个数组属性nums,然后再<li>元素上使用v-for指令遍历该数组这将循环渲染<li>元素。在v-for块中,可以访问所有父作用域的属性,num是数组中的元素别名,每次循环,num的值都被重置为数组当前索引的值,在<li>元素内部,可以通过插值来引用该变量。

注意:v-for指令表达式也可以使用of替换in作为分隔符

v-for 指令的表达式还可以支持一个可选的参数作为当前项的索引 演示代码:

<template>
  <div id="app">
    <ul>
      <li v-for="(num ,index) in nums">{{index}}-{{num.title}}</li>
    </ul>
    <router-view />
  </div>
</template>
<script>
export default {
  name: 'App',
  data() {
    return {
      nums: [{ title: '1' }, { title: '2' }, { title: '3' }]
    }
  }
}
</script>

运行结果

image.png

过滤与排序

有时想要显示一个数据经过过滤或排序后的版本,但不实际改变或重置原始数据。在这种情况下,可以创建一个计算属性,来返回过滤或排序后的数组。

演示代码:

<template>
  <div id="app">
    <ul>
      <li v-for="num  in evennums">{{num}}</li>
    </ul>
    <router-view />
  </div>
</template>
<script>
export default {
  name: 'App',
  data() {
    return {
      nums: [1, 2, 3, 4, 5]
    }
  },
  computed: {
    evennums: function () {
      return this.nums.filter(function (nums) {
        return nums % 2 === 0
      })
    }
  }
}
</script>

在计算属性不适用的情况下也可以使用一个方法。

演示代码:

<template>
  <div id="app">
    <ul>
      <li v-for="num  in evennums(numbers)">{{num}}</li>
    </ul>
    <router-view />
  </div>
</template>
<script>
export default {
  name: 'App',
  data() {
    return {
      nums: [1, 2, 3, 4, 5]
    }
  },
  methods: {
    evennums: function (numbers) {
      return this.nums.filter(function (nums) {
        return nums % 2 === 0
      })
    }
  }
}
</script>

运行结果:

image.png 关于计算属性和方法我们后面再详细讲

遍历整数

v-for指令也可以接受整数。在这种情况下他会把模板重复对应次数。

演示代码:

<template>
  <div id="app">
    <ul>
      <li v-for="num  in 10">{{num}}</li>
    </ul>
    <router-view />
  </div>
</template>

运行结果:

image.png