其他分享
首页 > 其他分享> > vue_列表渲染v-for

vue_列表渲染v-for

作者:互联网

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style type="text/css">
    .activated {color: red}
  </style>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
  <div id="app">
    <!-- 列表渲染 v-for  -->
    <!-- v-for="(item[, index]) of list"  item 表示当前项,index可选,表示当先项的下标-->
    <!-- key:唯一的,提升性能 -->
    <!-- 动态添加数据 不能使用下标插数据 
      vm.list[3] = {goodsId:"0004", "goodsPrice": "¥1299.00"}数据发生该变,但是不会渲染页面
      动态改变必须通过遍历方法改变,例如push pop slice 数组的方法,或者直接改变数组引用vm.list = [{},{},{}]
      -->
    <button @click="handleIndexLoad">下标动态加载数据</button>
    <button @click="handleForeachload">遍历动态加载数据</button>
    <div v-for="(item, index) of list" 
         :key="item.goodsId"
      >
      <span>{{item.goodsPrice}}</span>
      <span>---{{index}}</span>
    </div>
    <p>渲染占位符 只会渲染template包裹的元素</p>
    <template v-for="(item, index) of list">
      <span>{{item.goodsPrice}}</span>
      <span>---{{index}}</span>
    </template>
    <p>对象遍历</p>
    <!-- v-for='(value[, key, index]) of listObj' -->
    <!-- 
      value,对象每个属性的值
      key,对象每个属性
      index,下标索引
     -->
    <!-- 动态添加数据 不能像js一样直接添加属性obj.key = value 数据会发生改变但页面不会渲染 -->
    <template v-for="(value, key, index) of listObj" :key="value">
      <p>{{value}} --- {{key}} --- {{index}}</p>
    </template>
  </div>
</body>
<script type="text/javascript">
  let vm = new Vue({
    el: '#app',
    data: {
      list: [{
        "goodsId": "0001",
        "goodsPrice": "¥5899.00"
      },{
        "goodsId": "0002",
        "goodsPrice": "¥3599.00"
      },{
        "goodsId": "0003",
        "goodsPrice": "¥1299.00"
      }],
      listObj: {
        "goodsId": "0001",
        "goodsPrice": "¥5899.00",
        "goodsInfo": "直降500元!到手价5899元!享12期免息!低至16.2元/天",
        "goodsShop": "华为京东自营官方旗...",
        "goodsImg": "http://..............."
      }

    },
    methods: {
      handleIndexLoad () {
        this.list[this.list.length] = {
          "goodsId": '000'+(this.list.length + 1),
          "goodsPrice": "¥399.00"
        }
        console.log(this.list)
      },
      handleForeachload () {
        this.list.push({
          "goodsId": '000'+(this.list.length + 1),
          "goodsPrice": "¥399.00"
        })
        console.log(this.list)
      }
    }
  })
  
</script>
</html>

 

标签:index,vue,渲染,list,length,列表,goodsId,goodsPrice
来源: https://www.cnblogs.com/JunLan/p/12419378.html