【问题标题】:Want to run function on 1st route when user will go from 1st route to 2nd and 2nd to 1st route in Vue and Vuex当用户在 Vue 和 Vuex 中从第一条路线转到第二条路线和第二条路线到第一条路线时,想要在第一条路线上运行功能
【发布时间】:2019-03-09 10:30:22
【问题描述】:

我想在加载的路线(第一条路线)上运行一个函数,然后转到第二条路线。用户再次从第二条路线转到第一条路线。

当用户在 Vue 和 Vuex 中从第二条路线转到第一条路线时,我想在第一条路线上运行一个函数。

我尝试过像 Created、beforeMount 这样的 Vue 生命周期钩子,但它们都不起作用。

你能告诉我我需要运行什么以及它将如何在 Vue 项目上运行。

谢谢

【问题讨论】:

    标签: vue.js vuejs2 vuex vue-router


    【解决方案1】:

    vue-router navigation guards 你可以定义全局钩子来调用beforeEach 路由器更改或afterEach

    例如,pre-route guard 的示例:

    //router.js
    
    const router = new VueRouter({
      routes: [
        {
          path: '/night',
          component: nightComponent,
          beforeEnter: (to, from, next) => {
            const currentHour = new Date().getHours();
            if(currentHour < 6){
                next(); // this function will trigger the routing. in my example, i 
                       //call it only if its not morning yet.
            }
          }
        }
      ]
    })
    

    您还可以定义一个in-component guard,以对该特定路线的更改采取措施。

    new Vue({
      el: "#app",
      router,
      data: {},
      methods: {},
      beforeRouteLeave (to, from, next) {
        // called when the route that renders this component is about to
        // be navigated away from.
        // has access to `this` component instance.
           if(confirm('are you sure you want to leave this page?')){
               next();
            }
          }
       }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-13
      • 2021-04-30
      • 1970-01-01
      • 2012-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多