如何获取V-Calendar组件当前选中的月份值
获取V-Calendar当前选中月份的方法
核心思路:监听page-change事件
V-Calendar提供了page-change事件,会在用户切换月份/年份时触发,返回的参数直接包含当前选中的月份和年份信息。
修正你的代码并实现功能
注意你当前用的是Vue Options API,data()里不需要用ref(),直接返回普通对象即可。以下是完整的修改示例:
<template> <v-calendar :initial-page="initialPage" :attributes="attributes" @page-change="handlePageChange" /> <!-- 展示当前选中的月份信息 --> <div>当前选中:{{ currentYear }}年{{ currentMonth + 1 }}月</div> </template> <script> export default { data() { return { // 初始化页面(V-Calendar的initial-page中month是1-12格式) initialPage: [{ month: new Date().getMonth() + 1, year: new Date().getFullYear() }], attributes: [ { dot: { style: { backgroundColor: '#DD2C00', }, }, dates: [ // new Date(2023, 9, 12), // new Date(2023, 3, 26), // new Date(2023, 5, 15), // new Date(2023, 6, 15), ], }, ], // 存储当前选中的年月(month为0-11格式,和JS Date一致) currentYear: new Date().getFullYear(), currentMonth: new Date().getMonth() }; }, methods: { handlePageChange(page) { // 更新当前选中的年月 this.currentYear = page.year; this.currentMonth = page.month; // 这里可以根据年月请求对应数据、更新页面内容 console.log('当前选中月份:', `${page.year}年${page.month + 1}月`); } } }; </script>
关键细节说明
page-change返回的page对象中,month是0索引格式(0代表1月),展示时需要加1转换为1-12的常用格式- 初始化时的
initialPage里,month是1-12格式,和事件返回的格式有区别,注意区分 - 在
handlePageChange函数中,你可以直接使用page.year和page.month去处理对应月份的业务逻辑,比如请求该月的数据、渲染相关内容
内容的提问来源于stack exchange,提问作者MYBLUE
相关产品推荐
相关产品推荐

