>  기사  >  웹 프론트엔드  >  Vue에서 테이블 헤더와 첫 번째 열을 수정하는 방법

Vue에서 테이블 헤더와 첫 번째 열을 수정하는 방법

亚连
亚连원래의
2018-06-08 13:48:283956검색

이 글에서는 테이블 헤더와 첫 번째 열을 수정하기 위한 샘플 코드를 구현하는 Vue의 다양한 방법을 주로 소개하고 참고용으로 제공합니다.

테이블이 너무 커서 스크롤할 때 정보를 보는 것이 불편할 때가 있습니다.

효과는 다음과 같습니다.

1.

아이디어: 페이지가 임계 값으로 스크롤되면 고정 헤더와 첫 번째 열이 나타납니다

먼저 활성 테이블을 만들고

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
      th,
      td {
        min-width: 200px;
        height: 50px;
      }
      #sTable {
        margin-top: 300px
      }
      [v-cloak]{
        display: none;
      }
    </style>
  </head>
  <body v-cloak>
    <!--活动的表格-->
    <table id="sTable" border="1" cellspacing="0">
      <thead>
        <tr>
          <th v-for="item in th">{{item.key}}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in tl">
          <td v-for="list in item">{{list.key}}</td>
        </tr>
      </tbody>
    </table>
    <script src="vue.js"></script>
    <script src="jquery.js"></script>
    <script>
      var vm = new Vue({
        el: "body",
        data: function() {
          return {
            th: [],
            tl: [],
            temp: [],
          }
        },
        methods: {
          //生成表格
          CTable: function() {
            for(var i = 0; i < 10; i++) {
              this.th.push({
                key: "head" + i
              })
            }
            for(var i = 0; i < 100; i++) {
              for(var j = 0; j < 10; j++) {
                this.temp.push({
                  key: j + "body" + i
                })
              }
              this.tl.push(this.temp)
              this.temp = []
            }
          },
        },
        ready: function() {
          this.CTable();
        },
      })
    </script>
  </body>
</html>

그런 다음 고정 헤더를 추가하세요.

#fHeader {
  background: lightblue;
  position: fixed;
  top: 0;
}
<!--固定表头-->
<table border="1" id="fHeader" cellspacing="0" v-show="fixedHeader"> 
  <thead>
    <tr >
      <th v-for="item in th">{{item.key}}</th>
    </tr>
  </thead>
</table>

고정 헤더는 다음과 같은 경우에 나타납니다. 모니터링 테이블 위치가 창 상단에 도달합니다

//监控表头位置
headerMonitor:function(){
  var self=this
  var hHeight=$("#sTable").offset().top;
  $(document).scroll(function(){
    //当滚动条达到偏移值的时候,出现固定表头
    if($(this).scrollTop()>hHeight){
      self.fixedHeader=true
    }else{
      self.fixedHeader=false
    }
  })
}

물론 필수입니다. 이 메서드를

ready: function() {
  this.CTable();
  this.headerMonitor()
},

호출한 다음 고정된 첫 번째 열과 고정된 A1 셀을 추가합니다

#fHeader {
  background: lightblue;
    position: fixed;
    top: 0;
    z-index: 1;
  }
  .fixedA1{
    background: lightblue;
    position: fixed;
    top: 0;
    left: 0;
    z-index:2;
  }
<!--固定A1-->
<table border="1" cellspacing="0" class="fixedA1" v-show="fixedA1">
  <thead>
    <tr>
      <th v-for="item in th" v-if="$index==0">{{item.key}}</th>
    </tr>
  </thead>
</table>
<!--固定首列-->
<table border="1" cellspacing="0" class="fixedCol" v-show="fixedCol">
  <thead>
    <tr>
      <th v-for="item in th" v-if="$index==0">{{item.key}}</th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="item in tl">
      <td v-for="list in item" v-if="$index==0">{{list.key}}</td>
    </tr>
  </tbody>
</table >

마찬가지로 테이블의 위치를 ​​모니터링합니다

//监控表头、首列位置
monitor:function(){
  var self=this
  $(document).scroll(function(){
    self.setPosition()
    //当滚动条达到左偏移值的时候,出现固定列头
    if($(this).scrollLeft()>self.hLeft){
      self.fixedCol=true
    }else{
      self.fixedCol=false
    }
    //当滚动条达到上偏移值的时候,出现固定表头
    if($(this).scrollTop()>self.hHeight){
      self.fixedHeader=true
    }else{
      self.fixedHeader=false
    }
    //当表格移到左上角时,出现固定的A1表格
    if($(this).scrollLeft()>self.hLeft&&$(this).scrollTop()>self.hHeight){
      self.fixedA1=true
    }else{
      self.fixedA1=false
    }
  })
},

움직이기 때문에 테이블의 헤더 위치가 테이블 헤더의 위치에 영향을 미치므로 현재 테이블의 오프셋을 변경해야 합니다. 이동된 값은 고정 헤더에 할당됩니다. 첫 번째 열

setPosition:function(){
  $("#fHeader").css("left",this.hLeft-$(document).scrollLeft())
  $(".fixedCol").css("top",this.hHeight-$(document).scrollTop())
}

Jq는 고정된 헤더와 첫 번째 열을 달성하기 위해 여러 테이블을 생성하기 위해 모니터링하고 스크롤합니다.html

2 고정된 헤더와 첫 번째 열을 달성하기 위해 스타일을 제어합니다

아이디어: 테이블이 임계 값에 도달할 때 , 헤더 변경, 첫 번째 열의 스타일

먼저 고정 헤더 구현

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
      th,
      td {
        min-width: 200px;
        height: 50px;
      }
      table {
        margin: 300px
      }
      .fHeader {
        background: lightblue;
        position: fixed;
        top: 0;
      }
      [v-cloak]{
        display: none;
      }
    </style>
  </head>
  <body v-cloak>
    <table border="1" cellspacing="0">
      <thead>
        <tr :class="{fHeader:fixedHeader}">
          <th v-for="item in th">{{item.key}}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in tl">
          <td v-for="list in item">{{list.key}}</td>
        </tr>
      </tbody>
    </table>
    <script src="vue.js"></script>
    <script src="jquery.js"></script>
    <script>
      var vm = new Vue({
        el: "body",
        data: function() {
          return {
            th: [],
            tl: [],
            temp: [],
            fixedHeader: false,
          }
        },
        methods: {
          //生成表格,代码相同,省略
          CTable: function() {},
          //监控表头位置
          headerMonitor:function(){
            var self=this
            var hHeight=$("table").offset().top;
            $(document).scroll(function(){
              //当滚动条达到偏移值的时候,出现固定表头
              if($(this).scrollTop()>hHeight){
                self.fixedHeader=true
              }else{
                self.fixedHeader=false
              }
            })
          }
        },
        ready: function() {
          this.CTable();
          this.headerMonitor()
        },
      })
    </script>
  </body>
</html>

고정된 첫 번째 열 추가

.fixedCol>:first-child{
  background: lightblue;
  position: fixed;
  z-index: 1;
  border:1px solid grey;
  left: 0;
  line-height: 50px;
}

테이블 위치 모니터링

//监控表头,首列位置
monitor:function(){
  this.setPosition()
  var self=this
  $(document).scroll(function(){
    self.setPosition();
    //当滚动条达到偏移值的时候,出现固定表头
    if($(this).scrollTop()>self.hHeight){
      self.fixedHeader=true;
    }else{
      self.fixedHeader=false
    }
    //当滚动条达到左偏移值的时候,出现固定列头
    if($(this).scrollLeft()>self.hLeft){
      self.fixedCol=true
    }else{
      self.fixedCol=false
    }
    //当表格移到左上角时,出现固定的A1表格
    if($(this).scrollLeft()>self.hLeft&&$(this).scrollTop()>self.hHeight){
      self.fixedA1=true
    }else{
      self.fixedA1=false
    }
  })
},

오프셋 값 설정

//使固定表头与列头的偏差与当前表格的偏移值相等
setPosition:function(){
  $(".fixedHeader").css("left",this.hLeft-$(document).scrollLeft())
  for(var i=0,len=this.tl.length+1;i<len;i++){
    //因为设置了“border-collapse:collapse”,所以要加“54-1”
    $(".fixedCol>:first-child").eq(i).css("top",this.hHeight-$(document).scrollTop()+53*i)
  }
}

헤더가 고정 위치가 되기 때문에 , 문서 흐름에서 벗어나 테이블 두 번째 행이 숨겨지므로 너비와 높이를 확장하려면 두 번째 열이 필요합니다

/*因为fixed定位不占位,当固定表头出现时,有一行会补到表头位置,即有一行跳空,将tbody的第一行行高加倍*/
.fixedHeaderGap:first-child>td{
    padding-top:54px;
  }
/*因为fixed定位不占位,当固定列头出现时,有一列会补到列头位置,即有一列跳空,将tbody的第二列p设置padding*/
.fixedCol>:nth-child(2){
  padding-left: 205px;
}

페이지가 다시 브라우저에서 열릴 때 여부를 모니터링해야 합니다. 테이블이 여전히 고정 헤더의 위험 상태에 도달합니다

watch:{
  //页面初始加载时,使固定表头与列头的偏差与当前表格的偏移值相等
  "fixedHeader":function(){
    this.setPosition()
  },
  "fixedCol":function(){
    this.setPosition()
  },
},

고정을 달성하기 위해 스타일을 변경합니다. 거의 사용되지 않으며 Vue 관계자는 Dom 요소 작동을 권장하지 않으므로 사용자 정의 지침에서 고정 헤더와 첫 번째 열을 구현할 수 있습니다. 이 글은 Vue.js v1.0.26을 사용하고 있지만, V2.0의 아이디어는 사실 똑같습니다.

코드로 바로 이동

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
      th,
      td {
        min-width: 200px;
        height: 50px;
      }
      #sTable {
        margin: 300px
      }
      .fixedCol{
        position: fixed;
        left: 0;
        background: lightblue;
        z-index: 1;
      }
      #fHeader {
        background: lightblue;
        position: fixed;
        top: 0;
        z-index: 1;
      }
      .fixedA1{
        background: lightblue;
        position: fixed;
        top: 0;
        left: 0;
        z-index:2;
      }
      [v-cloak]{
        display: none;
      }
    </style>
  </head>
  <body v-cloak>
    <!--固定A1-->
    <table border="1" cellspacing="0" class="fixedA1" v-show="fixedA1">
      <thead>
        <tr>
          <th v-for="item in th" v-if="$index==0">{{item.key}}</th>
        </tr>
      </thead>
    </table>
    <!--固定列头-->
    <table border="1" cellspacing="0" class="fixedCol" v-show="fixedCol">
      <thead>
        <tr>
          <th v-for="item in th" v-if="$index==0">{{item.key}}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in tl">
          <td v-for="list in item" v-if="$index==0">{{list.key}}</td>
        </tr>
      </tbody>
    </table >
    <!--固定表头-->
    <table border="1" id="fHeader" cellspacing="0" v-show="fixedHeader"> 
      <thead>
        <tr >
          <th v-for="item in th">{{item.key}}</th>
        </tr>
      </thead>
    </table>
    <!--活动的表格,绑定自定义指令-->
    <table id="sTable" border="1" cellspacing="0" v-scroll>
      <thead>
        <tr>
          <th v-for="item in th">{{item.key}}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in tl">
          <td v-for="list in item">{{list.key}}</td>
        </tr>
      </tbody>
    </table>
    <script src="vue.js"></script>
    <script>
      var vm = new Vue({
        el: "body",
        data: function() {
          return {
            th: [],
            tl: [],
            temp: [],
            fixedCol: false,
            fixedHeader:false,
            fixedA1:false,
            hLeft:0,
            hHeight:0,
          }
        },
        directives:{
          scroll:{
            bind:function(){
              //触发滚动监听事件
              window.addEventListener(&#39;scroll&#39;,function(){
                this.vm.monitor()
              })
            }
          }
        },
        methods: {
          //生成表格
          CTable: function() {},
          //监控表头、列头位置
          monitor:function(){
            this.setPosition();
            //当滚动条达到左偏移值的时候,出现固定列头
            if(document.body.scrollLeft>this.hLeft){
              this.fixedCol=true;
            }else{
              this.fixedCol=false;
            }
            //当滚动条达到上偏移值的时候,出现固定表头
            if(document.body.scrollTop>this.hHeight){
              this.fixedHeader=true;
            }else{
              this.fixedHeader=false;
            }
            //当表格移到左上角时,出现固定的A1表格
            if(document.body.scrollLeft>this.hLeft&&document.body.scrollTop>this.hHeight){
              this.fixedA1=true;
            }else{
              this.fixedA1=false;
            }
          },
          //使固定表头与列头的偏差与当前表格的偏移值相等
          setPosition:function(){
            document.getElementById("fHeader").style.left=this.hLeft-document.body.scrollLeft+"px";
            document.getElementsByClassName("fixedCol")[0].style.top=this.hHeight-document.body.scrollTop+"px";
          },
        },
        ready: function() {
          this.CTable();
          this.hLeft=document.getElementById("sTable").offsetLeft;
          this.hHeight=document.getElementById("sTable").offsetTop
          this.monitor()
        },
      })
    </script>
  </body>
</html>
맞춤 콜백 이벤트를 만들고 싶다면 eval()을 사용하면 됩니다.

<table id="sTable" border="1" cellspacing="0" v-scroll="monitor">
directives:{
  scroll:{
    bind:function(){
      var self=this;
      //触发滚动监听事件
      window.addEventListener(&#39;scroll&#39;,function(){
        //触发滚动回调事件
        eval("self.vm."+self.expression)()
      })
    }
  }
},

맞춤 콜백 명령어를 사용하여 테이블 열을 수정할 수 있습니다.header.html

위 내용은 제가 컴파일한 내용입니다. 여러분, 앞으로도 잘 활용되었으면 좋겠습니다. 모두에게 도움이 되었습니다.

관련 기사:

Bootstrap에서 테이블 병합 셀을 구현하는 방법

JavaScript에서 선택 드롭다운 상자의 첫 번째 값을 가져오는 방법

실시간으로 비밀번호를 가져오고 표시하는 방법 AngularJS

위 내용은 Vue에서 테이블 헤더와 첫 번째 열을 수정하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.