vue-router demo

by leos0331

HTML

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<!-- Include the library in the page -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha256-pasqAKBDmFT4eHoN2ndd6lN370kFiGUFyTiUHWhU7k8=" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script src="https://unpkg.com/vue-router"></script>

<!-- App -->
<div id="app">
  <nav>
    <router-link :to="{ name: 'modal' }" exact>Open Modal</router-link>
    <router-link to="/home" exact>Home</router-link>
    <router-link to="/nested-modal">Nested modal</router-link>
  </nav>

  <router-view></router-view>
</div>

<script type="text/x-template" id="home-page">
  <div>
  	<h2>Home</h2>
  </div>
</script>

<script type="text/x-template" id="nested-modal-page">
  <div>
  	<router-link :to="{ name: 'modal' }" exact>Open Modal</router-link>    
  </div>
</script>

JavaScript

console.clear()

Vue.use(VueRouter)

const Home = {
  template: '#home-page'
};

const NestedModal = {
  template: '#nested-modal-page'
}

const Modal = {
  template: `<div class="modal fade" tabindex="-1" role="dialog" ref="modal">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p>Modal body text goes here.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>`,

  mounted: function() {
    console.log('mounted')

    var context = this;

    $(this.$refs.modal).modal('show')

    $(this.$refs.modal).on('hidden.bs.modal', function() {
      context.$router.go(-1);
    })
  }
}


const routes = [{
    path: '/modal',
    name: 'modal',
    component: Modal
  },
  {
    path: '/home',
    component: Home
  },
  {
    path: '/nested-modal',
    component: NestedModal
  }
];

const router = new VueRouter({
  mode: 'history',
  routes,
})

// New VueJS instance
var app = new Vue({
  // CSS selector of the root DOM element
  el: '#app',
  // Inject the router into the app
  router,
})