• Vue之vue-router实现路由


    1、安装路由插件

    npm install --save vue-router

    2、在components目录下编写两个vue组件,home.vue和about.vue

    <template>
      <div>
        <h1>about</h1>
        <p>{{aboutMsg}}</p>
      </div>
    </template>
    <script>
      export default {
        data () {
          return {
            aboutMsg: '我是about组件'
          }
        }
      }
    </script>
    <template>
      <div>
        <h1>home</h1>
        <p>{{msg}}</p>
      </div>
    </template>
    <script>
      export default {
        data () {
          return {
            msg: "我是home 组件"
          }
        }
      }
    </script>

    3、在src目录下面创建router.js文件

    import Vue from "vue";
    import VueRouter from "vue-router";
    
    // 引入组件
    import home from "./components/home.vue";
    import about from "./components/about.vue";
    
    // 要告诉 vue 使用 vueRouter
    Vue.use(VueRouter);
    
    const routes = [
      {
        path:"/home",
        component: home
      },
      {
        path: "/about",
        component: about
      }
    ]
    
    var router =  new VueRouter({
      routes
    })
    export default router;

    4、在main.js中添加一下几行

    // The Vue build version to load with the `import` command
    // (runtime-only or standalone) has been set in webpack.base.conf with an alias.
    import Vue from 'vue'
    import App from './App'
    import  router from './router.js'
    Vue.config.productionTip = false
    /* eslint-disable no-new */
    new Vue({
      el: '#app',
      router,
      components: { App },
      template: '<App/>',
    
    })

    5、在App.vue引用组件

    <template>
      <div id="app">
        <img src="./assets/logo.png">
    <!--    <HelloWorld/>-->
        <br/>
        <header>
          <!-- router-link 定义点击后导航到哪个路径下 -->
          <router-link to="/home">Home</router-link>
          <router-link to="/about">About</router-link>
        </header>
        <!-- 对应的组件内容渲染到router-view中 -->
        <router-view></router-view>
      </div>
    </template>
    
    <script>
    import HelloWorld from './components/HelloWorld'
    import MyVue from  './components/MyVue'
    export default {name: 'App',
      components: {HelloWorld,
        MyVue
    }  //组件注册
    
    }
    </script>
    
    <style>
    #app {
      font-family: 'Avenir', Helvetica, Arial, sans-serif;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      text-align: center;
      color: #2c3e50;
      margin-top: 60px;
    }
    </style>
  • 相关阅读:
    webpackHotMiddleware改造成koa支持的中间件
    webpack-dev-middleware改造成koa中件间
    Vue3学习笔记
    当前工程中typescritpt依赖包与依赖包中依赖包类型不一致如何解决
    typescript中使用Object.keys
    获取东8区时间
    SyntaxError: Invalid regular expression: invalid group specifier name
    测试代码框
    ST Lab2 Selenium
    ST HW3
  • 原文地址:https://www.cnblogs.com/ywjfx/p/12370826.html
Copyright © 2020-2023  润新知