vue-Material-Year-Calendar插件:activeDates.push后日歷未更新選中狀態(tài)的解決方法
使用Vue-Material-Year-Calendar插件時,常常遇到一個問題:將日期添加到activeDates數(shù)組后,日歷界面未更新選中狀態(tài)。本文將分析問題原因并提供解決方案。
問題描述:
按照官方文檔,使用activeDates.sync綁定activeDates數(shù)組,并通過自定義方法向數(shù)組添加日期信息。但即使activeDates數(shù)組已包含該日期,日歷界面仍未顯示選中狀態(tài)。
立即學習“前端免費學習筆記(深入)”;
代碼示例(Vue 2):
<yearcalendar :activeclass="activeclass" :activedates.sync="activedates" prefixclass="your_customized_wrapper_class" v-model="year"></yearcalendar> data() { return { year: 2019, activedates: [ { date: '2019-02-13' }, { date: '2019-02-14', classname: 'red' }, // ... ], activeclass: '', } }, toggledate(dateinfo) { const index = this.activedates.indexOf(dateinfo); if (index === -1) { this.activedates.push(dateinfo); } else { this.activedates.splice(index, 1); } }
問題根源及解決方案:
問題在于Vue 2和Vue 3中.sync修飾符的使用差異。
Vue 2解決方案: 移除.sync修飾符,直接使用:activedates:
<yearcalendar :activeclass="activeclass" :activedates="activedates" prefixclass="your_customized_wrapper_class" v-model="year"></yearcalendar>
Vue 3解決方案: 使用ref并添加selected屬性:
const activeDates = ref([ { date: '2024-02-13', selected: true, className: '' }, { date: '2024-02-14', className: 'red' }, // ... ]); const toggledate = (dateinfo) => { const index = activeDates.value.findIndex(item => item.date === dateinfo.date); if (index === -1) { activeDates.value.push({...dateinfo, selected: true}); } else { activeDates.value.splice(index, 1); } };
通過以上修改,日歷界面將正確反映activeDates數(shù)組的更改。 toggledate函數(shù)的邏輯也需要根據(jù)實際需求調(diào)整,例如在push新日期時,顯式設(shè)置selected: true。 Vue 3 的例子中使用了 findIndex 來更精確地查找日期,避免了潛在的比較對象不一致的問題。 也使用了展開運算符 …dateinfo 來避免直接修改原對象,保持數(shù)據(jù)的一致性。
? 版權(quán)聲明
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載。
THE END