source

클릭 시 Vue 목록 항목

goodcode 2022. 8. 13. 12:11
반응형

클릭 시 Vue 목록 항목

이 Vue 앱이 있어요.

var app = new Vue({
  el: '#main',
  delimiters: ['${', '}'],
  data () {
      posts: [
          {
            id: 1,
            title: 'Post title 1',
            description: 'Post description 1'
          },
          {
            id: 2,
            title: 'Post title 2',
            description: 'Post description 2'
          },
          {
            id: 3,
            title: 'Post title 3',
            description: 'Post description 3'
          }
      ],
  },
  methods: {
      getPostData: function (event) {

      }
  }
});

 <div id="main">
  <ul>
    <li v-for="(post, index) in posts"><a @click="getPostData">${ post.title }</a></li>
  </ul>
</div>
Here go description from clicked item

리스트내의 아이템을 클릭해, 이 아이템의 설명을 # item-description div 에 표시하고 싶습니다.

클릭 항목에서 설명을 가져오도록 이 getPostData를 프로그래밍하는 방법.

Tnx

<div id="main">
  <ul>
     <li v-for="(post, index) in posts"><a @click="getPostData(post.description)">${ post.title }</a></li>
  </ul>
</div>

 methods: {
   getPostData: function (postDesc) {
     // you got the post Desc
   }
 }

현재 선택한 항목 또는 설명을 저장해야 합니다.템플릿에서 메서드를 호출하고 항목을 매개 변수로 전달하면 이 작업을 수행할 수 있습니다.예:

var app = new Vue({
    el: '#main',
    data() {
        return {
            posts: [{
                id: 1,
                title: 'Post title 1',
                description: 'Post description 1'
            }, {
                id: 2,
                title: 'Post title 2',
                description: 'Post description 2'
            }, {
                id: 3,
                title: 'Post title 3',
                description: 'Post description 3'
            }],
            currentDescription: null
        };
    },
    methods: {
        setDescription(item) {
            this.currentDescription = item.description;
        }
    }
});

<div id="main">
  <ul>
    <li v-for="(post, index) in posts">
      <a @click="setDescription(post)">${ post.title }</a>
    </li>
  </ul>
</div>

<div id="item-description">{{ currentDescription }}</div>

클릭 한 번으로 새 데이터를 비동기식으로 가져오려면setDescription방법.


편집:

설명 자체보다 게시물의 ID를 저장하는 것이 더 나을 수 있습니다.이 경우 설명뿐만 아니라 게시물 전체에 액세스할 수 있습니다.그런 다음 전류가 다음 중 하나인지 확인할 수 있습니다.<li>활성 상태 등입니다.여기 이것의 예가 있다.이 예에서는 계산된 속성을 사용하여 일반 속성처럼 액세스할 수 있습니다.그것들은 현재 상태에서 파생됩니다.그렇게,currentPost액티브 ID 가 설정되어 있는 경우는, 항상 현재 선택된 투고가 표시됩니다.currentDescription다음에, 의 설명을 읽습니다.currentPost. 이러한 속성은 일반 상태 속성과 동일한 방법으로 액세스할 수 있습니다.

var app = new Vue({
    el: '#main',
    data() {
        return {
            posts: [{
                id: 1,
                title: 'Post title 1',
                description: 'Post description 1'
            }, {
                id: 2,
                title: 'Post title 2',
                description: 'Post description 2'
            }, {
                id: 3,
                title: 'Post title 3',
                description: 'Post description 3'
            }],
            currentId: null
        };
    },
    methods: {
        setCurrentId(id) {
            this.currentId = id;
        }
    },
    computed: {
        currentPost() {
           if (this.currentId !== null) {
               const currentPostInArray = this.posts.filter(post => {
                  return post.id === this.currentId;
               });
               if (currentPostInArray.length === 1) {
                   return currentPostInArray[0];
               }
           }
           return null;
        },
        currentDescription() {
            if (this.currentPost !== null) {
                return this.currentPost.description;
            }
            return null;
        }
    }
});

<div id="main">
  <ul>
    <li v-for="(post, index) in posts" :class="{ active: post.id === currentId }">
      <a @click="setCurrentId(post.id)">${ post.title }</a>
    </li>
  </ul>
</div>

<div id="item-description">{{ currentDescription }}</div>

참고로:투고 전체를 ID가 아닌 복사본으로 데이터에 저장하는 것은 권장되지 않습니다.계산된 속성을 사용하면 이 속성은 항상 최신 상태로 유지되므로 걱정할 필요가 없습니다.예를 들어, 예를 들어,posts현재 선택된 게시물을 배열하고 해당 게시물에서 제거합니다.currentPost다른 아무것도 업데이트하지 않고 null 값이 됩니다.또는 설명을 변경하는 경우:계산된 속성은 항상 올바른 항목(업데이트된 설명 포함)을 제공합니다.

언급URL : https://stackoverflow.com/questions/53409694/vue-list-item-on-click-details

반응형