Uso detallado de Vue v-for

Vue de instrucciones v-fory keypropiedades.

1. Iterar la matriz

<ul>
  <li v-for="(item, i) in list">索引:{
    
    {
    
    i}} --- 姓名:{
    
    {
    
    item.name}} --- 年龄:{
    
    {
    
    item.age}}</li>
</ul>

2. Itere los atributos en el objeto

	<!-- 循环遍历对象身上的属性 -->
    <div v-for="(val, key, i) in userInfo">{
    
    {
    
    val}} --- {
    
    {
    
    key}} --- {
    
    {
    
    i}}</div>

3. Números iterativos

<p v-for="i in 10">这是第 {
    
    {
    
    i}} 个P标签</p>

4. Bucle de matriz ordinaria

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="./lib/vue-2.4.0.js"></script>
</head>

<body>
  <div id="app">
    <!-- <p>{
    
    {
    
    list[0]}}</p>
    <p>{
    
    {
    
    list[1]}}</p>
    <p>{
    
    {
    
    list[2]}}</p>
    <p>{
    
    {
    
    list[3]}}</p>
    <p>{
    
    {
    
    list[4]}}</p> -->

    <p v-for="(item, i) in list">索引值:{
    
    {
    
    i}} --- 每一项:{
    
    {
    
    item}}</p>

  </div>

  <script>
    // 创建 Vue 实例,得到 ViewModel
    var vm = new Vue({
    
    
      el: '#app',
      data: {
    
    
        list: [1, 2, 3, 4, 5, 6]
      },
      methods: {
    
    }
    });
  </script>
</body>

</html>

5. Bucle la matriz de objetos

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="./lib/vue-2.4.0.js"></script>
</head>

<body>
  <div id="app">
    <p v-for="(user, i) in list">Id:{
    
    {
    
     user.id }} --- 名字:{
    
    {
    
     user.name }} --- 索引:{
    
    {
    
    i}}</p>
  </div>

  <script>
    // 创建 Vue 实例,得到 ViewModel
    var vm = new Vue({
    
    
      el: '#app',
      data: {
    
    
        list: [
          {
    
     id: 1, name: 'zs1' },
          {
    
     id: 2, name: 'zs2' },
          {
    
     id: 3, name: 'zs3' },
          {
    
     id: 4, name: 'zs4' }
        ]
      },
      methods: {
    
    }
    });
  </script>
</body>

</html>

6. Objeto de bucle

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="./lib/vue-2.4.0.js"></script>
</head>

<body>
  <div id="app">
    <!-- 注意:在遍历对象身上的键值对的时候, 除了 有  val  key  ,在第三个位置还有 一个 索引  -->
    <p v-for="(val, key, i) in user">值是: {
    
    {
    
     val }} --- 键是: {
    
    {
    
    key}} -- 索引: {
    
    {
    
    i}}</p>
  </div>

  <script>
    // 创建 Vue 实例,得到 ViewModel
    var vm = new Vue({
    
    
      el: '#app',
      data: {
    
    
        user: {
    
    
          id: 1,
          name: '托尼·颗',
          gender: '男'
        }
      },
      methods: {
    
    }
    });
  </script>
</body>

</html>

7. Iterar números

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="./lib/vue-2.4.0.js"></script>
</head>

<body>
  <div id="app">
    <!-- in 后面我们放过  普通数组,对象数组,对象, 还可以放数字 -->
    <!-- 注意:如果使用 v-for 迭代数字的话,前面的 count 值从 1 开始 -->
    <p v-for="count in 10">这是第 {
    
    {
    
     count }} 次循环</p>
  </div>

  <script>
    // 创建 Vue 实例,得到 ViewModel
    var vm = new Vue({
    
    
      el: '#app',
      data: {
    
    },
      methods: {
    
    }
    });
  </script>
</body>

</html>

En la versión 2.2.0+, cuando se usa v-for en componentes, ahora se requiere la clave.

Cuando Vue.js usa v-for para actualizar la lista de elementos renderizados, usa la estrategia de " reutilización in situ " de forma predeterminada . Si se cambia el orden de los elementos de datos, Vue no moverá los elementos DOM para que coincidan con el orden de los elementos de datos, sino que simplemente reutilizará cada elemento aquí y se asegurará de que muestre cada elemento que se ha representado bajo un índice específico.
Para darle a Vue una pista para que pueda rastrear la identidad de cada nodo, reutilizando y reordenando los elementos existentes, debe proporcionar un atributo clave único para cada elemento.

Código completo:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="./lib/vue-2.4.0.js"></script>
</head>

<body>
  <div id="app">

    <div>
      <label>Id:
        <input type="text" v-model="id">
      </label>

      <label>Name:
        <input type="text" v-model="name">
      </label>

      <input type="button" value="添加" @click="add">
    </div>

    <!-- 注意: v-for 循环的时候,key 属性只能使用 number获取string -->
    <!-- 注意: key 在使用的时候,必须使用 v-bind 属性绑定的形式,指定 key 的值 -->
    <!-- 在组件中,使用v-for循环的时候,或者在一些特殊情况中,如果 v-for 有问题,必须 在使用 v-for 的同时,指定 唯一的 字符串/数字 类型 :key 值 -->
    <p v-for="item in list" :key="item.id">
      <input type="checkbox">{
    
    {
    
    item.id}} --- {
    
    {
    
    item.name}}
    </p>
  </div>

  <script>
    // 创建 Vue 实例,得到 ViewModel
    var vm = new Vue({
    
    
      el: '#app',
      data: {
    
    
        id: '',
        name: '',
        list: [
          {
    
     id: 1, name: '李斯' },
          {
    
     id: 2, name: '嬴政' },
          {
    
     id: 3, name: '赵高' },
          {
    
     id: 4, name: '韩非' },
          {
    
     id: 5, name: '荀子' }
        ]
      },
      methods: {
    
    
        add() {
    
     // 添加方法
          this.list.unshift({
    
     id: this.id, name: this.name })
        }
      }
    });
  </script>
</body>

</html>

Si no usa la clave

Después de agregar un nuevo elemento, verifique el número de índice correspondiente y aparecerá un error

Pero si usa la clave, no habrá tales errores, al igual que Xunzi

Supongo que te gusta

Origin blog.csdn.net/weixin_46034375/article/details/108454267
Recomendado
Clasificación