javascript - jQuery在使用vue.js插入后按类获取元素
问题描述
如果您查看我的演示代码,您将看到一个名为 scrollToCurrentMonth() 的函数,它试图滚动到 listTemplate 中具有“当前”类的元素。我的问题是我无法获取此元素,因为它已通过 vue.js 插入到 dom 中。那么如何使用“current”类获取此元素,以便获得滚动动画的顶部位置?
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>
解决方案
尝试使用mounted而不是created。
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
}, 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>
推荐阅读
- javascript - 从第 n 个孩子计数中排除 display:none div
- php - mysql如何允许用户使用php一次更新数据库中的列
- pycharm - 从自包导入会出现未解决的错误
- python - Python基础知识,数据框迭代 - 计算平均评分数
- javascript - 刷新页面时,数据会保留在 localStorage 中,但是会从显示中消失
- python - 如何从 github 安装模块?
- javascript - 删除收藏夹列表中的某个项目后如何动态呈现配置文件视图以反映reactjs应用程序中的更改?
- javascript - 在 laravel 中将数据库导出到 csv 不起作用,“无法访问该站点”
- javascript - 无法读取未定义的属性“AddControll”
- tensorflow - 召回和精度无法正常工作(keras)