css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <div id="app">
  <h1>Vue Router Navigation Guards Explained</h1>


  <nav class="mainNav">
    <!-- use router-link component for navigation. -->
    <router-link :to="{ name: 'home'}">Home</router-link>
    <!-- specify the link by passing the `to` prop. -->
    <router-link :to="{ name: 'user', params: { userId: 1} }">User One</router-link>
    <router-link :to="{ name: 'user', params: { userId: 2} }">User Two</router-link>
    <router-link :to="{ name: 'user', params: { userId: 3} }">User Three</router-link>
    <router-link :to="{ name: 'bar'}">Bar</router-link>
    <router-link :to="{ name: 'foo'}">Foo</router-link>
    <router-link :to="{ name: 'error'}">Error</router-link>
  </nav>
  <!-- route outlet -->
  <!-- component matched by the route will render here -->
  <section class="mainBody">
    <router-view></router-view>
  </section>
  
</div>
            
          
!
            
              #app {
  max-width: 800px;
  margin: auto;
}

code {
  background: #f2f2f2;
  padding: 0 0.5rem;
}

.mainBody {
  border-top: 1px solid #ddd;
  border-bottom: 1px solid #ddd;
  margin: 1rem 0;
  padding: 1rem 0;
}

nav.mainNav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  > * {
    flex: 1;
    display: flex;
    justify-content: center;
    text-decoration: none;
  }
  
  > *:nth-last-child(n+2) {
    border-right: 1px solid #aaa;
  }
}
            
          
!
            
              /* ===========================================
              Our Pretend User Data
=========================================== */

const userList = {
  1: {
    userName: 'Peter Parker',
    heroName: 'Spiderman'
  },
  2: {
    userName: 'Bruce Banner',
    heroName: 'Hulk'
  },
  3: {
    userName: 'Tony Stark',
    heroName: 'Ironman'
  }
}

/* ===========================================
              Our Components
=========================================== */

const Home = {
  template: `
    <section>This is the home screen.</section>
  `
} 

const Foo = {
  template: `
    <section>You will not see this template when Foo is redirected to Home.</section>
  `
} 

const Err = {
  template: `
    <section>
      You will not see this template. The error is passed to our error handler.
    </section>
  `
} 

const Bar = { 
  template: `
    <section>
      <div>Bar - <span @click="testFunc" style="color: #cc0000; cursor: pointer;">testFunc()</span></div>
    </section>
  `,
  // set guard on the component options object:
  beforeRouteEnter ( to, from, next ) {
    // console.log('Entering Bar')
    
    // Pass a callback to next (optional)
    next(vm => {
      // this callback has access to component instance (ie: 'this') via `vm`
      vm.testFunc('Some Message', true)
      // console.log("Fully Entered Bar")
    })
  },
  // set guard on the component options object:
  beforeRouteLeave ( to, from, next ) {
    // console.log('Leaving Bar')
    next()
  },
  methods: {
    testFunc(msg, fromGuard = false) {
      fromGuard ? console.log(`This message called from the guard: ${msg}`) : console.log(`This message called from component.`)
    }
  }
}

/* ===========================================
        This User Component will be Reused
=========================================== */
const User = {
  props: ["userId"],
  template: `
    <div>
      <div v-if="user">User - {{user.userName}}({{userId}}) = {{user.heroName}}</div>
    </div>
  `,
  data() {
   return {
     user: {
       userName: '',
       heroName: ''
     }
   }
  },
  mounted() {
    this.user = this.getUser(this.userId)
  },
  methods: {
    getUser(id) {
      // console.log('Fetching User')
      return userList[id]
    }
  },
  // set guard on the component options object:
  beforeRouteLeave ( to, from, next ) {
    // console.log('Leaving User')
    next(false)
  },
  /* Called when this component is reused.
  Here we have a chance to update the component
  since mounted() and other life-cycle hooks won't be called 
  when a component is reused. */
  beforeRouteUpdate ( to, from , next ) {
    // console.log('Reusing this component.')
    this.user = this.getUser(to.params.userId)
      // console.log('Entering User', to.params.userId)
    
    next()
  }
}

/* ===========================================
              Per-route Guards
=========================================== */

const routes = [
  { path: '/', name: 'home', component: Home},
  { path: "/bar", name: 'bar', component: Bar },
  { path: "/foo", name: 'foo', component: Foo },
  { path: "/error", name: 'error', component: Err },
  {
    path: "/user/:userId",
    name: "user",
    component: User,
    props: true,
    // set nav guard on the route definition object:
    beforeEnter: (to, from, next) => {
      console.log('Entering User', to.params.userId)
      to.params.myCustomizations = {
        
      }
      next()
    }
  }
  
]

const router = new VueRouter({
  routes // short for routes: routes
})

/* ===========================================
              GLOBAL GUARDS
 =========================================== */

// GLobal BEFORE hooks:
router.beforeEach((to, from, next) => {
  // console.log('Global -- beforeEach - fired')
  
  // re-route
  if (to.path === '/foo') {
    next('/')
  } 
  // Abort navigation based on some criteria:
  // else if (to.path === '/user/1') {
  //   next(false)
  // } 
  else if (to.path === '/error') {
    const err = new Error('My Error Message')
    
    // pass the error to onError() callback.
    next(err)
  }
  else {
    next()
  }
})

// Global beforeResolve 
router.beforeResolve((to, from, next) => {
  // console.log('Global -- beforeResolve - fired.')
  next()
})

// GLobal AFTER hooks:
router.afterEach((to, from) => {
  // This fires after each route is entered.
  // console.log(`Global -- afterEach - Just moved from '${from.path}' to '${to.path}'`)
})

// Register an Error Handler:
router.onError(err => {
  console.error('Handling this error', err.message)
})


// mount the app
const app = new Vue({
  router
}).$mount("#app")

            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console