Vue.js实现页面加载时每日仅弹出一次模态框的方法求助
Hey there! Let's figure out how to make your modal pop up only once per day when the site loads. Both localStorage and cookies are great options—here's a step-by-step breakdown for each, tailored to your Vue project:
LocalStorage is straightforward to work with—we'll store the last date the modal was shown, then compare it to the current date on page load. If they don't match (or there's no record), we'll show the modal and update the stored date.
Vue 2 (Options API) Example:
<script> export default { data() { return { modalVisible: false }; }, mounted() { this.checkDailyModal(); }, methods: { checkDailyModal() { // Format current date to YYYY-MM-DD (ignore time to avoid false mismatches) const today = new Date().toISOString().split('T')[0]; const lastShownDate = localStorage.getItem('lastModalShownDate'); // Show modal if no record exists, or if it wasn't shown today if (!lastShownDate || lastShownDate !== today) { this.modalVisible = true; localStorage.setItem('lastModalShownDate', today); } } } }; </script>
Vue 3 (Composition API) Example:
<script setup> import { ref, onMounted } from 'vue'; const modalVisible = ref(false); onMounted(() => { checkDailyModal(); }); function checkDailyModal() { const today = new Date().toISOString().split('T')[0]; const lastShownDate = localStorage.getItem('lastModalShownDate'); if (!lastShownDate || lastShownDate !== today) { modalVisible.value = true; localStorage.setItem('lastModalShownDate', today); } } </script>
Cookies let us set an expiration time directly—we'll set the cookie to expire at the end of the day, so it automatically clears itself overnight. On page load, we just check if the cookie exists.
Vue 2 (Options API) Example:
<script> export default { data() { return { modalVisible: false }; }, mounted() { this.checkDailyModal(); }, methods: { // Helper to set a cookie with expiration setCookie(name, value, expires) { document.cookie = `${name}=${value}; expires=${expires.toUTCString()}; path=/`; }, // Helper to get a cookie by name getCookie(name) { const cookieParts = `; ${document.cookie}`.split(`; ${name}=`); return cookieParts.length === 2 ? cookieParts.pop().split(';').shift() : null; }, checkDailyModal() { const hasShownToday = this.getCookie('modalShownToday'); if (!hasShownToday) { this.modalVisible = true; // Set cookie to expire at 23:59:59 today const endOfDay = new Date(); endOfDay.setHours(23, 59, 59, 999); this.setCookie('modalShownToday', 'true', endOfDay); } } } }; </script>
Vue 3 (Composition API) Example:
<script setup> import { ref, onMounted } from 'vue'; const modalVisible = ref(false); onMounted(() => { checkDailyModal(); }); function setCookie(name, value, expires) { document.cookie = `${name}=${value}; expires=${expires.toUTCString()}; path=/`; } function getCookie(name) { const cookieParts = `; ${document.cookie}`.split(`; ${name}=`); return cookieParts.length === 2 ? cookieParts.pop().split(';').shift() : null; } function checkDailyModal() { const hasShownToday = getCookie('modalShownToday'); if (!hasShownToday) { modalVisible.value = true; const endOfDay = new Date(); endOfDay.setHours(23, 59, 59, 999); setCookie('modalShownToday', 'true', endOfDay); } } </script>
- LocalStorage Pros: Simpler code, doesn't get sent to the server with every request. Cons: No automatic expiration—relies on date checks, and clears if the user wipes browser storage.
- Cookies Pros: Automatic expiration, works in older browsers (though localStorage is widely supported now). Cons: Gets included in HTTP requests (but the data here is tiny, so no performance hit).
- Edge Case Handling: Wrap storage operations in
try/catchblocks to handle cases where users have disabled localStorage/cookies:try { localStorage.setItem('lastModalShownDate', today); } catch (e) { console.error('LocalStorage is disabled:', e); // Fallback: show the modal anyway, or skip it this.modalVisible = true; }
Either approach will work perfectly for your daily modal requirement—pick the one that fits your project's needs best!
内容的提问来源于stack exchange,提问作者Persival

