source

Vue 메서드 스크롤 div를 맨 위로 이동

goodcode 2022. 7. 28. 23:52
반응형

Vue 메서드 스크롤 div를 맨 위로 이동

배우고 있다vue채팅 메시지를 div에 추가하는 방법은 다음과 같습니다.id="toolbar-chat"이 div는 y축 스크롤이 가능하며 새로운 메시지가 추가될 때마다 div가 맨 위로 점프했으면 합니다.JS가 작동하지 않는 이유는 무엇입니까?

    document.getElementById("toolbar-chat").scrollTop = 0;

나의vue방법:

    methods: {
        addMessage(message) {
            this.messages.unshift(message);

            document.getElementById("toolbar-chat").scrollTop = 0;

            axios.post(chat_send_route, message)
            .then(response => {
                console.log(response.data);
            });

        }
    }

이 문제는 vue가 dom을 비동기적으로 업데이트하기 때문에 발생합니다.자세한 내용은 "Reacivity in detail"(Async 업데이트 대기열)을 참조하십시오.

  • 변경 내용을 즉시 반영하려면vm.$nextTick(callback)

  • dom 요소를 쿼리하는 대신document.getElementById()를 추가할 것을 권장합니다.ref귀속toolbar-chat를 사용하여 메서드에서 참조합니다.this.$refs자세한 내용은 문서를 참조하십시오.ref기여하다

     <div id="toolbar-chat" ref="toolbarChat"></div>
    

그래서 당신의 방법은

methods: {
    addMessage(message) {
        this.messages.unshift(message);
        this.$nextTick(() => {
            this.$refs.toolbarChat.scrollTop = 0;
        });

        axios.post(chat_send_route, message)
        .then(response => {
            console.log(response.data);
        });

    }
}

여기 작동 중인 바이올린입니다.

다음은 저의 해결책입니다.

메인 컨테이너에 글로벌 div 1개

<div id="topDiv"></div>

Vue 프로토타입에 포함된 글로벌 기능:

Vue.prototype.$scrollTop = function () {
  var element = document.getElementById("topDiv");
  var top = element.offsetTop;
  window.scrollTo(0, top);
}

어디에서나 같은 앵커:

<a @click="$scrollTop">Go to the top</a>

이것은 오래된 것이지만, 나처럼 해결책을 찾고 싶은 사람에게는 다음과 같습니다.

addMessage(message) {
    this.messages.unshift(message);
    this.$nextTick(() => {
        // block: 'end' will scroll to top of element instead of bottom
        this.$refs.toolbarChat.$el.scrollIntoView({ block: 'end', scrollBehavior: 'smooth' });
    });

    axios.post(chat_send_route, message)
    .then(response => {
        console.log(response.data);
    });

}

애니메이션 방식으로 스크롤하려면

  • 개체 매개 변수를 사용하여 scrolllTo
  • 참조 요소를 확인합니다(이 경우는 $refs[refName][0]).
  • 스크롤을 하나 더 사용해야 하는 경우 전역 범위에 추가합니다.(Vue.protype).$toScroll)은 ($toScroll()을 사용합니다.

기본 사용법은 다음과 같습니다.

<a @click="toScroll('aKeyValue',0)"></a>

<div  :ref="'aKeyValue'"  class="scrollable">...</div>

이게 방법이에요. 어디서든 쓸 수 있어요.

toScroll(refName,position){
   this.messages.unshift(message);
   this.$nextTick(() => {
       this.$refs[refName][0].scrollTo({ top: position, behavior: 'smooth' });
   });
}

이걸 이용해서 작동시켰어요

document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera

언급URL : https://stackoverflow.com/questions/45658042/vue-method-scroll-div-to-top

반응형