Vue学习之路由转发
1、路由(routing)是通过网络把信息从源地址传输到目标地址的路径叫路由。 2、路由器就提供了两种机制:路由和转发。路由是决定数据包从源地址到目标位地的路径。转送将输入端的数据转发到输出端。 3、路由中有一个重要的概念叫做路由表。路由表本质上就是一张后端映射表,决定了url的指向路径。一般是由后端就行封装。
随着网页开发目前基本是前后端分离时代。由于Ajax(异步 JavaScript 和 XML)的出现,就有了前后端分离的开发模式。后端只需要提供接口来返回数据,前端就通过Ajax获取到数据,并且通过JavaScript将数据渲染到页面当中。
Vue路由转发学习小总结
总体的目录结构如下,
1.创建自定义vue组件 Content.vue
//1.写组件中的内容
<template>
<div>
<h1>我是一个content</h1>
</div>
</template>
<script>
//2.暴露组件 export
export default {
name: "Content"
}
</script>
<style scoped>
</style>
(1)暴露组件 export
(2)写组件中的内容 template中
要先定义一个div,然后在里面写
2.创建路由 index.js
import Vue from 'vue';
//导入路由
import VueRouter from 'vue-router';
//导入自定义的组件import
import Content from '../components/Content';
//导入自定义的组件import
import Main from '../components/Main';
//使用路由
Vue.use(VueRouter);
//暴露vue路由接口
export default new VueRouter({
//写需要转发的已经导入的路由routes
routes: [
{
//路由路径
path: '/content',
name: content,
//跳转组件
component: Content
},
{
path: '/main',
name: main,
component: Main
}
]
})
(1)在src目录下创建一个路由包router
(2)创建index.js(官方推荐)然后导入路由
(3)导入自定义的组件import
(4)使用路由
(5)暴露vue路由接口
(6)写需要转发的已经导入的路由routers
(7)path路由路径
(8)component跳转组件
3.在Main.js中配置路由
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/>'
})
(1)导入路由配置目录router
(2)在Vue中配置路由
4.在App.vue中引入路由
<template>
<div id="app">
<router-link to="/main">首页</router-link>
<router-link to="/content">内容</router-link>
//写上router-view才能看到使用的组件的内容
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App',
}
</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>
(1)引入使用自定义vue组件
(2)浏览组件内容
完成后,在项目当前路径下打开控制台输入
npm run dev
然后在浏览器打开可以得到
然后点击首页
或者点击内容
所以这个时候第一个使用了Vue路由转发的小项目就搭建成功了,大家在公司里面有做到路由相关的业务,就可以用vue的这种方式来进行开发,我手中的一个项目业务就是根据登录人的不同展示不同的菜单页面,用到的就是以上的开发模式。
请关注“知了堂学习社区”,地址:https://zhiliaotang.cn