1. 程式人生 > 其它 >Vue指令03——v-bind和v-for的使用

Vue指令03——v-bind和v-for的使用

Vue指令03——v-bind和v-for

v-bind命令

效果:更改元素屬性,如 src、title、href

格式:v-bind:屬性=”變數“

格式::屬性=”變數“

修改行類樣式1

<!--繫結樣式-->
<div id="app">
  <!-- 繫結樣式屬性值 -->
  <div v-bind:style="{backgroundColor:pink,width:width,height:height}">
         <!-- 繫結樣式物件 -->
         <div v-bind:style=“myDiv”></div>
  </div>
</div>

<script>
var app=new Vue({
    el:"#app",
    data: {
    //變數名:值
     pink:'pink',
     width:'100%', 
     height: '200px'
     
       //字典型資料,駝峰寫樣式
      myDiv:{
      backgroundColor: 'red', 
      width: '100px',
      height: '100px‘ 
   }
        
}

    })
</script>
<body>
    <!--繫結樣式-->
    <style>
        .box1 {
            background-color: pink;
            width: 500px;
            height: 600px;
        }

        #box2 {
            background-color: red;
            width: 100px;
            height: 100px;
        }

        .box3 {
            margin-top: 20px;
            background-color: blue;
            width: 100px;
            height: 100px;
        }
    </style>

    <div id="app" :class="B1">
        <div :id="B2"> </div>
        <div :class="B3"> </div>
    </div>

    <script>
        var app = new Vue({
            el: "#app",
            data: {
                B1: "box1",
                B2: "box2",
                B3: "box3"
            }

        })
    </script>
</body>

v-for命令

作用:自動新增元素

格式1:v-for="變數 in 陣列/值"

格式2:v-for="(變數,下標變數) in 陣列"

this.陣列名.push(資料) //在陣列最後新增資料

this.陣列名.shift() //刪除陣列最後的資料

this.陣列名.splice(下標,1); //刪除陣列指定的資料 ,1代表刪1條

<div id="acc">
    <button @click="add">按鈕+</button>
    <button @click="rm">按鈕—</button>
<ul>
     <!--把陣列arr的值賦給變數it,index為下標變數-->
    <li v-for="(it,index) in arr">{{index}}_{{it}}</li> 
     <!--把陣列vc的值賦值給info-->
    <li v-for="info in vc">{{info.name}}</li>

</ul>

</div>
<script>
    var info=new Vue({
        el:"#acc",
        data:{
            //陣列1
            arr:["好運來!","好運離開","痛苦棘手"],  
            //  陣列2,值是物件
            vc:[{name:"小明"},{name:"小紅"}]
        },
        methods:{
           add:function(){
               //push:在陣列後新增值
            this.vc.push({name:1234})
           },
           rm:function(){
               //shift:從陣列左邊移出值
               this.vc.shift()
           }
        }
    })
</script>