Home  >  Q&A  >  body text

javascript - Will Vue trigger an event when refreshing the page?

I just learned Vue not long ago. I made a simple note according to the online demo, using localstorage for local storage. Then I want to call the localstorage method when refreshing the page or leaving the page. Can this be achieved? If so, how? Thank you for your answer, I appreciate it!

曾经蜡笔没有小新曾经蜡笔没有小新2637 days ago1948

reply all(3)I'll reply

  • 世界只因有你

    世界只因有你2017-07-05 11:08:39

    Generally when developing using Vue, you don’t need to touch window.onload such DOM-related APIs. Instead, use the component life cycle hook encapsulated by Vue:

    export default {
      // ...
      // 在组件初始化时调用,可以简单理解为页面加载时
      created () {
        // 存在 localStorage 的缓存内容
        if (localStorage.data) {
          this.myData = JSON.parse(localStorage.data)
        }
        else {
          // 页面无缓存内容时,初始化数据并写入缓存
          this.initData()
        }
      }
      // 在组件销毁前调用,但这并不能监听到页面退出的事件
      beforeDestory () {
        // 在此同样可对 localStorage 做一些处理
      }
    }

    reply
    0
  • 巴扎黑

    巴扎黑2017-07-05 11:08:39

    Use life cycle functions, choose which one to use according to your needs, refer to https://cn.vuejs.org/v2/api/#Options-Life Cycle Hook

    reply
    0
  • 滿天的星座

    滿天的星座2017-07-05 11:08:39

    Use localstorage for local storage, and then I want to call the localstorage method when refreshing the page or leaving the page

    1. Use localstorage for page refresh, that is, after Vue is instantiated, the following are available for you to use:

    export default {
        beforecreate() {
            //  创建前状态
        }
        created () {
            //  创建完毕状态
        }
        beforeMount(){
            //  挂载前状态
        }
        mounted(){
            //  挂载结束状态
        }
    }
    

    These can operate local storage when the page is refreshed.
    Note: In fact, local storage does not need to be written in the vue instance. It essentially has nothing to do with vue. You just execute a piece of js when the page is refreshed

    main.js

    /* 项目启动 */
    import Vue from 'vue'
    import App from './App'
    import router from './router'
    
    /****************************
     写这里也不是不可以
    ****************************/
    new Vue({
      router: router,
      render: h => h(App)
      // components: { firstcomponent, secondcomponent }
    }).$mount('#app')
    

    2. Page closing has nothing to do with the life cycle of vue, and there is no such thing as destruction. Therefore, there is no way for you to operate localStorage when closing the page. This is different from what the people above said.

    reply
    0
  • Cancelreply