Vue练习一:01_01_控制div属性

Demo 在线地址:

https://sx00xs.github.io/test/1/index.html

---------------------------------------------------------------

ide: vscode

文件格式:.vue

需求:5 个按钮,分别控制 1 个 100px * 100px 的 div 的各种属性(变宽/变高/变色/隐藏/重置)

模板:

1  input 元素中,使用 v-for render 出 5 个按钮。

2  input元素绑定 click 事件,并传入 index 参数,用于判定进行何种操作

3  div 元素 使用 v-bind绑定 style 至 styleObject,这是一个对象,用于下面设定 div 的宽/高/背景色 属性。

4  div 元素 使用 v-show指令绑定数据 show,这是一个bool值,用于设定 div 元素的 显示/隐藏。

脚本:

1,data 数据:

a show,用于 v-show指令,显示/隐藏 div

b styleObject,对象,用于绑定 div 的style内联样式

c buttonsval,用于v-for指令,提供按钮的 value

2, 方法:

handleChange,此方法接收一个参数:index ,即按钮索引,用于判定按钮应执行何种操作。
方法中使用switch,根据传入的 index 分别执行相应操作。

----------------------------------------------------------------

<template>
  <div id="outer">
    <input 
    type="button" 
    v-for="(val,index) in buttonsval" 
    :value="val" 
    :key="val"
    @click="handleChange(index)"
    />
    <div class="div1" :style="styleObject" v-show="show"></div>
  </div>
</template>
<script>
export default {
  data(){
    return{
      show:true,
      styleObject:{
        width:'',
        height:'',
        background:''
      },
      buttonsval:[
        '变宽',
        '变高',
        '变色',
        '隐藏',
        '重置'
      ],
      
    }
  },
  methods:{
    handleChange(index){
      switch(index){
        case 0:
          this.styleObject.width='200px';
          break;
        case 1:
          this.styleObject.height='200px';
          break;
        case 2:
          this.styleObject.background='red';
          break;
        case 3:
          this.show=false;
          break;
        case 4:
          this.styleObject.width='100px';
          this.styleObject.height='100px';
          this.styleObject.background='black';
          this.show=true;
      }
    }
  }
}
</script>

猜你喜欢

转载自www.cnblogs.com/sx00xs/p/11264423.html