Vue中使用vue-router

Vue中使用vue-router

    • 1. 安装vue-router
    • 2. 创建路由页面
    • 3. 创建router文件
    • 4. 挂载router
    • 5. 使用

1. 安装vue-router

npm install [email protected] --save

2. 创建路由页面

HomeView.vue

<template>
  <div>homediv>
template>

<script>
  export default {
    name:'HmeView',
    data(){
      return{}
    },
    methods:{},
    created(){},
    mounted(){}
 }
script>

<style lang=scss>
style>

About.vue

<template>
  <div>aboutdiv>
template>

<script>
  export default {
    name:'About',
    data(){
      return{}
    },
    methods:{},
    created(){},
    mounted(){}
 }
script>

<style lang=scss>
style>

3. 创建router文件

  • 创建router文件夹,并创建index.js
//引入vue和vue-router
import Vue from 'vue'
import VueRouter from 'vue-router'
//引入路由页面
import HomeView from '../views/HomeView.vue'
import VideoView from '../views/VideoView.vue'


Vue.use(VueRouter)

//定义路由
const routes = [
  {
    path:'/',
    name:'home',
    component: HomeView
  },
  {
    path:'/about',
    name:'about',
    component:()=>import(/*webpackChunkName:"about"*/'../views/About.vue')
  }
]
//创建路由
const router = new VueRouter({
	//模式
	mode:'history',
	//使用定义的路由
	routes
})

export default router

4. 挂载router

main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'

Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App),
}).$mount('#app')

5. 使用

App.vue

<template>
	<div id='app'>
		<!-- 使⽤router-link组件来导航 -->
		<!-- 通过传⼊to属性指定连接 -->
		<!-- router-link默认会被渲染成⼀个a标签 -->
		<router-link to='home'>Home</router-link>
		<router-link :to={name:'about'}>About</router-link>
		<!-- 路由出⼝ 路由渲染位置 -->
		<router-view/>
	</div>
</template>

你可能感兴趣的:(Vue,vue.js,前端,javascript)