Vue series eleven: vue-router routing

11.1. Description


When learning, try to open the official documents as much as possible

Vue Router is the official routing manager for Vue.js. It is deeply integrated with the core of Vue.js, making building single-page applications a snap. Included features are:

  • Nested route/view table
  • Modular, component-based routing configuration
  • Routing parameters, queries, wildcards
  • View transition effect based on Vue js transition system
  • Fine-grained navigation control
  • Links with automatically activated CSS classes
  • HTML5 history mode or hash mode, automatically degraded in IE 9
  • Custom scrolling behavior

11.2. Installation

Test and learn based on the first one vue-cli; first check whether there is vue-router in node modules
  vue-router is a plug-in package, so we still need to use n pm/cn pm to install. Open the command line tool, go to your project directory and enter the following command.

npm install vue-router --save-dev

If you use it in a modular project, you must explicitly install the routing functionality via Vue.use() :

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

Vue.use(VueRouter);

11.3. Testing

1. Delete useless things first
2. componentsStore components written by ourselves in the directory
3. Define a Content.vuecomponent of

<template>
	<div>
		<h1>内容页</h1>
	</div>
</template>

<script>
	export default {
		name:"Content"
	}
</script>

Main.vuecomponents

	<template>
	<div>
		<h1>首页</h1>
	</div>
</template>

<script>
	export default {
		name:"Main"
	}
</script>

4. Install routing, create a new folder in the src directory: router, specially store routing, configure routing index.js, as follows

import Vue from'vue'
//导入路由插件
import Router from 'vue-router'
//导入上面定义的组件
import Content from '../components/Content'
import Main from '../components/Main'
//安装路由
Vue.use(Router) ;
//配置路由
export default new Router({
	routes:[
		{
			//路由路径
			path:'/content',
			//路由名称
			name:'content',
			//跳转到组件
			component:Content
			},{
			//路由路径
			path:'/main',
			//路由名称
			name:'main',
			//跳转到组件
			component:Main
			}
		]
	});

5. main.jsConfigure routing in

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

//导入上面创建的路由配置目录
import router from './router'//自动扫描里面的路由配置

//来关闭生产模式下给出的提示
Vue.config.productionTip = false;

new Vue({
	el:"#app",
	//配置路由
	router,
	components:{App},
	template:'<App/>'
});

6. App.vueUse routing in

<template>
	<div id="app">
		<!--
			router-link:默认会被渲染成一个<a>标签,to属性为指定链接
			router-view:用于渲染路由匹配到的组件
		-->
		<router-link to="/">首页</router-link>
		<router-link to="/content">内容</router-link>
		<router-view></router-view>
	</div>
</template>

<script>
	export default{
		name:'App'
	}
</script>
<style></style>

 

Guess you like

Origin blog.csdn.net/qq_21137441/article/details/123768331