提问者:小点点

jQuery在插入vue.js后按类获取元素


如果您查看我的演示代码,您将看到一个名为scrollToCurrentMonth()的函数,它试图滚动到ListTemplate中具有'current'类的元素。 我的问题是我无法获得这个元素,因为它已经通过vue.js插入到dom中。 那么,我如何获得这个元素与类'current',以便我可以得到它的顶部位置为滚动动画呢?

null

const listTemplate = '' +
'<div class="list_body">' +
    '<div v-for="(month, index) in months" v-bind:class="[\'event_month\', {current : index === currentMonth}]">' +
        '{{month}}' +
    '</div>' +
'</div>';

Vue.component('events-list-view', {
    template: listTemplate,
    data() {
        return {
            months:  ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
            currentMonth: new Date().getMonth(),
        };
    },
    created() {
        this.scrollToCurrentMonth();
    },
    methods: {
        scrollToCurrentMonth() {
            $('.list-wrap').animate({
                scrollTop: $('.list-wrap .current').offset().top
            }, 2000);
        }
    }
});

new Vue({ el: "#app" });
.list-wrap {
  max-height: 300px;
  overflow-y: scroll;
}

.event_month{
  height: 100px;
  border: 1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div class="list-wrap">
    <events-list-view />
  </div>
</div>

null


共1个答案

匿名用户

尝试使用mounted而不是created。

null

const listTemplate = '' +
'<div class="list_body">' +
    '<div v-for="(month, index) in months" v-bind:class="[\'event_month\', {current : index === currentMonth}]">' +
        '{{month}}' +
    '</div>' +
'</div>';

Vue.component('events-list-view', {
    template: listTemplate,
    data() {
        return {
            months:  ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
            currentMonth: new Date().getMonth(),
        };
    },
    mounted() {
        this.scrollToCurrentMonth();
    },
    methods: {
        scrollToCurrentMonth() {
            $('.list-wrap').animate({
                scrollTop: $('.list-wrap .current').offset().top
            }
        }
    }
});

new Vue({ el: "#app" });
.list-wrap {
  max-height: 300px;
  overflow-y: scroll;
}

.event_month {
  height: 100px;
  border: 1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div class="list-wrap">
    <events-list-view />
  </div>
</div>