Vue 3 页面第一次加载时才执行方法

2024-06-07  本文已影响0人  _浅墨_

在 Vue 3 中,如果你想在页面第一次加载时执行一次特定方法,然后再次加载页面时不再执行该方法,可以使用 localStoragesessionStorage 来存储一个标志,标识是否已经执行过该方法。

以下是一个示例,展示了如何在页面第一次加载时执行一次特定方法,并使用 localStorage 来存储执行状态。

示例代码

<template>
  <div>
    <p>{{ message }}</p>
    <button @click="resetExecution">重置执行状态</button>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';

export default {
  setup() {
    const message = ref('Hello, Vue!');

    const executeOnce = () => {
      console.log('This method is executed only once on the first load.');
      message.value = 'This message is set on the first load.';
    };

    const checkAndExecute = () => {
      const hasExecuted = localStorage.getItem('hasExecuted');
      if (!hasExecuted) {
        executeOnce();
        localStorage.setItem('hasExecuted', 'true');
      }
    };

    const resetExecution = () => {
      localStorage.removeItem('hasExecuted');
      message.value = 'Hello, Vue!';
      console.log('Execution status has been reset.');
    };

    onMounted(() => {
      checkAndExecute();
    });

    return {
      message,
      resetExecution
    };
  }
};
</script>

<style scoped>
/* 这里可以添加你的样式 */
</style>

解释

  1. ref

    • 使用 ref 创建响应式数据 message,用于显示在页面上。
  2. executeOnce 方法

    • 这是你希望在页面第一次加载时执行的方法。
    • 在这个示例中,它会输出一条日志并更新 message 的值。
  3. checkAndExecute 方法

    • 检查 localStorage 中是否存在 hasExecuted 标志。
    • 如果 hasExecuted 不存在,说明这是页面第一次加载,调用 executeOnce 方法,并将 hasExecuted 标志设置为 true
  4. resetExecution 方法

    • 用于重置执行状态,删除 localStorage 中的 hasExecuted 标志,并重置 message 的值。
    • 这个方法可以通过按钮点击来调用,用于测试和调试。
  5. onMounted 钩子

    • 在组件挂载时调用 checkAndExecute 方法,确保在页面第一次加载时执行特定方法。

总结

通过使用 localStorage 存储一个标志,你可以确保特定方法只在页面第一次加载时执行。下次加载页面时,检查到 localStorage 中已经存在标志,就不会再执行该方法。这种方式可以确保方法只执行一次,除非手动重置执行状态。

上一篇下一篇

猜你喜欢

热点阅读