Tìm hiểu về Vue router

VueJS là thư viện front-end có thể được sử dụng với bất kỳ ngôn ngữ back-end nào. Nếu muốn tạo ứng dụng front-end đầy đủ chức năng, thì vue-router và vue-resource là hai yếu tố chính tuyệt vời trong VueJS.

Bài viết hôm nay sẽ tìm hiểu sâu về Vue router. Routing (định tuyến) là cách để quản lý các thành phần trong Single Page Applications (SPA). Tất cả các framework front-end nổi tiếng đều sử dụng khái niệm Routing.

Vue router là gì?

Vue router là gì?

Vue router là router chính thức cho Vue.js. Nó tích hợp sâu với Vue.js core để giúp xây dựng các SPA với Vue.js một cách dễ dàng. Các tính năng bao gồm:

  • Nested route (định tuyến lồng nhau)/view mapping
  • Cấu hình router dựa trên thành phần, mô-đun
  • Định tuyến tham số, truy vấn, ký tự đại diện
  • Xem các hiệu ứng chuyển tiếp được cung cấp bởi hệ thống chuyển tiếp của Vue.js
  • Kiểm soát tính năng Fine-grained navigation
  • Liên kết với các active CSS class tự động
  • Chế độ HTML5 history mode hay hash mode, với tính năng auto-fallback trong IE9
  • Hành vi cuộn tùy chỉnh

Cách sử dụng vue-router

Bước 1: Tạo 3 component bên trong thư mục Components

Trong thư mục, tạo 3 file component. Các file này sẽ giống trong snippet sau:

// Home.vue

<template>
  <h1>Home</h1>
</template>

<script>
  export default {

  }
</script>

Sau đó tạo file About.vue.

// About.vue

<template>
  <h1>About us</h1>
</template>

<script>
  export default {

  }
</script>

Cuối cùng, tạo file Contact.vue.

// Contact.vue

<template>
  <h1>Contact us</h1>
</template>

<script>
  export default {

  }
</script>

Bước 2: Cập nhật file index.html và thêm thuộc tính app id.

<html>
    <body>
        <link rel = "stylesheet" href = "style.css"/>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
        <div id="app"></div>
        <script src = "main.js"></script>
    </body>
</html>

Bước 3: Cấu hình mô-đun vue-router

Trong file main.js, trước tiên, ta cần nhập mô-đun vue-router từ thư mục node_modules vì ta đã cài đặt tất cả các dependency trong dự án này. Sao chép code sau vào file main.js.

// main.js

import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

import Home from './components/Home.vue';
import About from './components/About.vue';
import Contact from './components/Contact.vue';

const router = new VueRouter({
  mode: 'history',
  base: __dirname,
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About },
    { path: '/contact', component: Contact }
  ]
});

new Vue({
  router,
  template: `
    <div>
      <nav class="navbar navbar-toggleable-md navbar-light bg-faded">
        <div class="collapse navbar-collapse" id="navbarNav">
          <ul class="navbar-nav">
            <li class="nav-item"><router-link to="/" class="nav-link">Home</router-link></li>
            <li class="nav-item"><router-link to="/about" class="nav-link">About</router-link></li>
            <li class="nav-item"><router-link to="/contact" class="nav-link">Contact</router-link></li>
          </ul>
        </div>
      </nav>
      <router-view class="view"></router-view>
    </div>
  `
}).$mount('#app');

Bước 4: Chạy code và xem đầu ra cuối cùng

Bây giờ, có 3 mục trong thanh Navigation và nếu bạn nhấp vào một trong số chúng, route bên dưới sẽ thay đổi và bạn có thể thấy ứng dụng vue-router hoạt động. Ví dụ đã bao gồm tất cả các file dự án chính ở đây cũng như (bạn cũng có thể tìm thấy dự án này trên Github: https://github.com/KrunalLathiya/playground-UjLAnHRe).

package.json

{
  "name": "vuerouter",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --host 0.0.0.0 --disable-host-check"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.25.0",
    "babel-loader": "^7.1.1",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-stage-3": "^6.24.1",
    "babel-runtime": "^6.25.0",
    "vue-loader": "^13.0.2",
    "vue-template-compiler": "^2.4.2",
    "webpack": "^3.4.1",
    "webpack-dev-server": "^2.6.1"
  },
  "dependencies": {
    "vue": "^2.4.2",
    "vue-router": "^2.7.0"
  }
}

webpack.config.js

var path = require('path');
module.exports = {
  // This is the "main" file which should include all other modules
  entry: path.join(__dirname,'/main.js'),
  // Where should the compiled file go?
  output: {
    filename: 'bundle.js'
  },
  resolve: {
  alias: {
    vue: 'vue/dist/vue.js'
  }
},
  module: {
    // Special compilation rules
    loaders: [
      {
        // Ask webpack to check: If this file ends with .js, then apply some transforms
        test: /\.js$/,
        // Transform it with babel
        loader: 'babel-loader',
        // don't transform node_modules folder (which don't need to be compiled)
        exclude: /node_modules/
      },
      {
        // Ask webpack to check: If this file ends with .vue, then apply some transforms
        test: /\.vue$/,
        // don't transform node_modules folder (which don't need to be compiled)
        exclude: /(node_modules|bower_components)/,
        // Transform it with vue
      use: {
        loader: 'vue-loader'
      }
    }
  ]
},
devServer: {
       port: 3000
   }
}

main.js

import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

import Home from './components/Home.vue';
import About from './components/About.vue';
import Contact from './components/Contact.vue';

const router = new VueRouter({
  mode: 'history',
  base: __dirname,
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About },
    { path: '/contact', component: Contact }
  ]
});

new Vue({
  router,
  template: `
    <div>
      <nav class="navbar navbar-toggleable-md navbar-light bg-faded">
        <div class="collapse navbar-collapse" id="navbarNav">
          <ul class="navbar-nav">
            <li class="nav-item"><router-link to="/" class="nav-link">Home</router-link></li>
            <li class="nav-item"><router-link to="/about" class="nav-link">About</router-link></li>
            <li class="nav-item"><router-link to="/contact" class="nav-link">Contact</router-link></li>
          </ul>
        </div>
      </nav>
      <router-view class="view"></router-view>
    </div>
  `
}).$mount('#app');

index.html

<html>
    <body>
        <link rel = "stylesheet" href = "style.css"  />
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
        <div id="app"></div>
        <script src = "bundle.js"></script>
    </body>
</html>

Home.vue

<template>
  <h1>Home</h1>
</template>

<script>
  export default {

  }
</script>

About.vue

<template>
  <h1>About us</h1>
</template>

<script>
  export default {

  }
</script>

Contact.vue

<template>
<h1>Contact us</h1>
</template>

<script>
  export default {

  }
</script>
Thứ Hai, 06/01/2020 11:15
52 👨 2.808
0 Bình luận
Sắp xếp theo