13——vue-router路由
首先要明白什么是路由:,路由是指根据URL分配到对应的处理程序。对于大多数单页面应用,都推荐使用官方支持的vue-router。Vue-router通过管理URL,实现URL和组件的对应,以及通过URL进行组件之间的切换。
-
由于是跟着狂神一路来的,所以要按视频要求打开之前创建的myvue项目,由于我打开错了项目,反正总之走了一晚上的弯路,
-
打开项目之后在控制台上执行
-
npm install vue-router --save-dev
-
因为vue-router在之前安装vue-cli的时候我们选择的是手动安装
-
-
然后删除一些项目不需要的东西,一个是Vue的logo,;一个是之前写的一个HelloWorld的组件
-
接着在src下一个名为components的文件夹下创建vue组件
-
一个叫content.vue
<template> <h1>内容页</h1> </template> <!-- </template> :用来放内容 <script> :用来放对象 --> <script> export default { name: "Content" } </script> <!--<style scoped> :表明其作用域只在本页--> <style scoped> </style>
-
一个叫Main.vue
<template> <h1>首页</h1> </template> <script> export default { name: "Main" } </script> <style scoped> </style>
-
-
在创建完组件以后,在src文件下创建一个叫router的文件夹,并新建一个index.js的文件
//index.js :是主配置页,不是通常意义上的首页 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 } ] });
- 这个index.js是用来配置路由的,也就是来管理Component(组件)的
-
之后在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/>'
})
- 再之后就是App.vue了,这是程序的主入口
<template>
<div id="app">
<!--
router-link:默认会被渲染成一个<a>标签,to属性为指定链接
router-view:用于渲染路由匹配到的组件
-->
<h1>-vuerouter</h1>
<router-link to="/main">首页</router-link>
<router-link to="/content">内容</router-link>
<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>
- 忘了说了,如果再安装完vue-router,执行npm install,执行npm run dev 命令,这时vue项目是热部署的,不出意外,在浏览器执行http://localhost:8080应该就会出现之前写的内容,如果没有执行这两个命令的话,那就现在执行吧先是执行npm install,再执行npm run dev 命令
- [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-b3pKm01H-1613875653754)(C:\Users\zp\Desktop\Vue\首页.jpg)]
以上就是执行成功界面,
ctrl+c,y,停止