vue路由的基本使用

vue路由是根据页面url的不同渲染不同的页面(组件)

  • 根据代码的步骤写一遍就会了
<!DOCTYPE html>
<html lang="en">

<head>
  <title></title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="./vue.js"></script>
  <!-- 第一步:引入组件 -->
  <script src="./vue-router.js"></script>
  <style>
    ul {
      display: flex;
    }

    li {
      list-style-type: none;
      padding: 0 20px;
    }
  </style>
</head>

<body>
  <div id="app">
    <ul>
      <!-- router-link组件专门用于页面跳转。它有一个to属性,里面的值必须和下面路由规则中的path一一对应,表示要跳转到的路径。将来这个router-link组件会被渲染为a标签,它的to属性的值会变为a标签的href属性值,并且加了# -->
      <li><router-link to="/home">首页</router-link> </li>
      <li><router-link to="/product">蔬菜</router-link></li>
      <li><router-link to="/product">蔬菜</router-link></li>
      <li><router-link to="/product">蔬菜</router-link></li>
    </ul>
    <!-- 6.通过router-view组件定义,用来放路由规则匹配到的组件,组件不要加name属性 -->
    <router-view></router-view>
  </div>
  <script>
    // 2.创建路由需要用到的组件
    let myhome = Vue.component('home', {
      template: `<div>首页</div>`
    })
    let myproduct = Vue.component('product', {
      template: `
              <div>
                商品分类
              </div>
        `
    })
    // 3.通过构造函数VueRouter()创建路由对象,这个构造函数又一个参数,他是一个对象
    let router = new VueRouter({
      // 4.1对象中routes属性输一个数组,可以用来放多了路由规则,每个路由规则是一个对象
      routes: [
        // 4.2对象中name表示路由规则名字,path表示路径,component表示路径匹配到的组件
        {
          name: 'index',
          path: '/home',
          component: myhome
        },
         {
          name: 'productCate',
          path: '/product',
          component: myproduct
        }
      ]
    })
    var vm = new Vue({
      el: '#app',
      // 5.路由对象注入实例
      router,
      data: {

      }
    })
  </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/Q_MUMU/article/details/85222502