[유인원설 VUE] 뷰 리스트 렌더링.

55201 단어 프런트엔드 VUE
8 VUE 베이스:목록 렌더링
우리는 v-for 명령을 사용하여 하나의 그룹을 바탕으로 목록을 렌더링할 수 있다.v-for 명령은 item in items 형식의 특수 문법을 사용해야 하는데 그 중에서 items는 원본 데이터 수조이고 item는 교체된 수조 요소의 별명이다.v-for 코드 블록에서 부작용역에 접근할 수 있는 속성은 아래 코드bookName를 참고하십시오.v-for는 선택할 수 있는 두 번째 인자 (index 를 지원한다. 즉, 전항의 인덱스에서 인덱스를 1로 추가한 결과를 책의 번호로 삼는 것이다.v-for 조작 대상: v-for로 한 대상의 속성을 훑어볼 수 있고 두 번째 파라미터는 property 이름(즉 키 이름)을 제공할 수 있다.세 번째 매개 변수index를 인덱스로 사용할 수도 있다.다음 예에서 참조: bookObject.

<html>
  <head>
    <meta charset="UTF-8">
    <title>VUE     title>

  head>
  <body>
    <div id='app'>
      <h2>v-for    h2>
      <ul>
        <li v-for="(book, index) in books" :key="index">
          {{index +1 }}____{{bookName}}{{book.name}}____{{bookPrice}}{{book.price}}
        li>
      ul>

      <hr>
      <h2>v-for    h2>
      <ul>
        <li v-for="(value, name, index) in bookObject">
           {{index+1}} : {{name}} : {{ value }}
        li>
      ul>
      
    div>
  body>

  <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
  <script type="text/javascript">
    const vm = new Vue({
      el : '#app',
      data : {
        bookName: '  :',
        bookPrice: '  :',
        books: [
          {name: 'Vue  ', price:28},
          {name: 'Vue  ', price:36},
          {name: 'Vue  ', price:69},
          {name: 'Vue      ', price:98}
        ],
        bookObject: {
          bookname: "Vue      ",
          price: 98,
          author: '   ',
          publishedAt: '2020-10-10'
        }
      }
    })
  script>

html>
Vue는 렌더링된 요소 목록v-for을 업데이트하는 동안 기본적으로 "현장 업데이트"정책을 사용합니다.데이터 항목의 순서가 바뀌면, Vue는 데이터 항목의 순서와 일치하도록 DOM 요소를 이동하지 않고, 그 자리에서 모든 요소를 업데이트하고, 색인 위치마다 정확하게 렌더링하도록 합니다.이 기본 모드는 효율적이지만 서브어셈블리 상태나 임시 DOM 상태(예: 양식 입력 값)를 따르지 않는 목록 렌더링 출력에만 적용됩니다.
각 노드의 ID를 추적하여 기존 요소를 재사용하고 순서재정리하려면 항목별로 고유Vue 속성을 제공해야 합니다.
가능한 한 key을 사용할 때v-forkey를 제공하십시오. 출력된 DOM 내용이 매우 간단하거나 기본 행동에 의존하여 성능 향상을 얻지 않는 한.
8.1 수조 업데이트 모니터링
변이 방법(mutation method): 말 그대로 이 방법들을 호출한 원시 그룹을 바꿉니다.Vue는 탐지된 그룹의 변이 방법을 감싸서 보기 업데이트를 터치합니다.이러한 포장된 변이 방법은 다음과 같다.
  • attribute
  • push()
  • pop()
  • shift()
  • unshift()
  • splice()
  • sort()
  • 컨트롤러를 열어 앞의 예 reverse() 의 그룹을 직접 변이 방법으로 호출할 수 있습니다.예컨대items.
    변이 방법에 비해 비변이(non-mutating method) 방법도 있다. 예를 들어 vm.books.push({name:"vue ", price: 38}),filter()concat().그것들은 원시 그룹을 바꾸지 않고 항상 새로운 그룹을 되돌려줍니다.비변이 방법을 사용할 때, 낡은 그룹을 새 그룹으로 바꿀 수 있다.Vue가 기존 DOM을 버리고 전체 목록을 다시 렌더링할 것이라고 생각할 수도 있습니다.다행히도 사실은 그렇지 않다.Vue는 DOM 요소를 최대한 범위에서 다시 사용하기 위해 지능적인 계발식 방법을 실현했기 때문에 같은 요소를 포함하는 수조로 원래의 수조를 교체하는 것은 매우 효율적인 작업이다.
    예제 코드 적용:
    
    <html>
      <head>
        <meta charset="UTF-8">
        <title>VUE     title>
    
      head>
      <body>
        <div id='app'>
          <h2>v-for    h2>
          <ul>
            <li v-for="(book, index) in books" :key="index">
              {{index +1 }}____{{bookName}}{{book.name}}____{{bookPrice}}{{book.price}} =======<button @click="delBook(index)">  button>
            li>
          ul>
          <button @click="addBook({name:'vue    ', price: 38})">    button>
    
          <hr>
          <h2>v-for    h2>
          <ul>
            <li v-for="(value, name, index) in bookObject">
               {{index+1}} : {{name}} : {{ value }}
            li>
          ul>
          
        div>
      body>
    
      <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
      <script type="text/javascript">
        const vm = new Vue({
          el : '#app',
          data : {
            bookName: '  :',
            bookPrice: '  :',
            books: [
              {name: 'Vue  ', price:28},
              {name: 'Vue  ', price:36},
              {name: 'Vue  ', price:69},
              {name: 'Vue      ', price:98}
            ],
            bookObject: {
              bookname: "Vue      ",
              price: 98,
              author: '   ',
              publishedAt: '2020-10-10'
            }
          },
          methods: {
            addBook(newbook){
              this.books.push(newbook);
            },
            delBook(index) {
              this.books.splice(index, 1);
            }
          },
        })
      script>
    
    html>
    
    이미 만들어진 실례에 대해 slice() 루트 단계의 응답식 속성을 동적으로 추가할 수 없습니다.단, Vue 방법으로 플러그인 대상에 응답식 속성을 추가할 수 있습니다.예를 들어,
    var vm = new Vue({
      data: {
        userProfile: {
          name: 'Anika'
        }
      }
    })
    
    Vue.set(object, propertyName, value) 속성을 끼워 넣은 age 대상에 추가할 수 있습니다.
    Vue.set(vm.userProfile, 'age', 27)
    
    너는 userProfile의 실례적인 방법을 사용할 수 있다. 그것은 전체 국면vm.$set의 별명일 뿐이다.
    vm.$set(vm.userProfile, 'age', 27)
    
    때때로 당신은 이미 있는 대상에 여러 개의 새로운 속성을 부여해야 할 수도 있습니다. 예를 들어 사용 Vue.set 이나 Object.assign().이런 상황에서, 너는 두 대상의 속성으로 새로운 대상을 만들어야 한다.따라서 새로운 응답 속성을 추가하려면 다음과 같이 하지 마십시오.
    Object.assign(vm.userProfile, {
      age: 27,
      favoriteColor: 'Vue Green'
    })
    
    너는 마땅히 이렇게 해야 한다.
    vm.userProfile = Object.assign({}, vm.userProfile, {
      age: 27,
      favoriteColor: 'Vue Green'
    })
    
    전체 코드:
    
    <html>
      <head>
        <meta charset="UTF-8">
        <title>VUE     title>
    
      head>
      <body>
        <div id='app'>
          <h2>v-for    h2>
          <ul>
            <li v-for="(book, index) in books" :key="index">
              {{index +1 }}____{{bookName}}{{book.name}}____{{bookPrice}}{{book.price}} =======<button @click="delBook(index)">  button>
            li>
          ul>
          <button @click="addBook({name:'vue    ', price: 38})">    button>
    
          <hr>
          <h2>v-for    h2>
          <ul>
            <li v-for="(value, name, index) in bookObject">
               {{index+1}} : {{name}} : {{ value }}
            li>
          ul>
          <hr>
          <h2>         h2>
          <ul>
            <li v-for="(value, name, index) in userProfile">
               {{index+1}} : {{name}} : {{ value }}
            li>
          ul>
          <button @click="addProperties">    button>
        div>
      body>
    
      <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
      <script type="text/javascript">
        const vm = new Vue({
          el : '#app',
          data : {
            bookName: '  :',
            bookPrice: '  :',
            books: [
              {name: 'Vue  ', price:28},
              {name: 'Vue  ', price:36},
              {name: 'Vue  ', price:69},
              {name: 'Vue      ', price:98}
            ],
            bookObject: {
              bookname: "Vue      ",
              price: 98,
              author: '   ',
              publishedAt: '2020-10-10'
            },
            userProfile: {
              name: '   '
            }
          },
          methods: {
            addBook(newbook){
              this.books.push(newbook);
            },
            delBook(index) {
              this.books.splice(index, 1);
            },
            addProperties(){
              vm.userProfile = Object.assign({}, vm.userProfile, {
                age: 27,
                favoriteColor: 'Vue Green'
              })
              console.log(vm.userProfile)
            }
          },
        })
      script>
    
    html>
    
    8.2 필터/정렬 결과 표시
    원본 데이터를 실제로 바꾸거나 리셋하지 않고 필터나 정렬을 거친 버전을 보여 드리려고 합니다.이 경우 필터나 정렬된 그룹을 되돌려 주는 계산 속성을 만들 수 있습니다._.extend() 목록 렌더링 명령은 프로젝트에서 자주 사용하지만 우리는 보통 백엔드 인터페이스에서 데이터를 받을 때 데이터를 순환 정리를 통해 원하는 모습으로 바꾼다.때때로 서로 다른 목록에 대한 수요에 따라 데이터에 데이터를 한 부 더 만들어야 하기 때문에 이런 방법은 매우 피곤하다.가장 좋은 방법은 v-for 순환할 때 데이터를 조작하여 원본 데이터가 변하지 않도록 유지하는 것이다.
    계산 속성 필터
    
    <html>
      <head>
        <meta charset="UTF-8">
        <title>VUE     title>
    
      head>
      <body>
        <div id="demo">
          <h2>h2>
          <input type="text" v-model="searchName">
          <ul>
            <li v-for="(p, index) in filterPersons" :key="index">
              {{index}}--{{p.name}}--{{p.age}}
            li>
          ul>
          <div>
            <button @click="setOrderType(2)">    button>
            <button @click="setOrderType(1)">    button>
            <button @click="setOrderType(0)">    button>
          div>
        div>
    
      body>
    
      <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
      <script type="text/javascript">
    
        const vm2 = new Vue({
          el: '#demo',
          data: {
            searchName: '',
            orderType: 0,     // 0     , 1    , 2    
            persons: [
              {name: 'Tom', age:18},
              {name: 'Jack', age:17},
              {name: 'Bob', age:19},
              {name: 'Mary', age:16}
            ]
          },
    
          computed: {
            filterPersons () {
              //       
              const {searchName, persons, orderType} = this
              let fPersons = [...persons]
              //     
              if(searchName.trim()) {
                fPersons = persons.filter(p => p.name.indexOf(searchName)!==-1)
              }
    
              //   
              if(orderType) {
                fPersons.sort(function (p1, p2) {
                  if(orderType===1) { //   
                    return p2.age-p1.age
                  } else { //   
                    return p1.age-p2.age
                  }
                })
              }
              return fPersons
            }
          },
    
          methods: {
            setOrderType (orderType) {
              this.orderType = orderType
            }
          }
        })
    
      script>
    html>
    

    좋은 웹페이지 즐겨찾기