本篇内容主要讲解“vue Router路由如何使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“vue Router路由如何使用”吧!
Vue Router 是 Vue.js 官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。路由实际上就是可以理解为指向,就是我在页面上点击一个按钮需要跳转到对应的页面,这就是路由跳转;
首先我们来学习三个单词(route,routes,router):
route:首先它是个单数,译为路由,即我们可以理解为单个路由或者某一个路由;
routes:它是个复数,表示多个的集合才能为复数;即我们可以理解为多个路由的集合,JS中表示多种不同状态的集合的形式只有数组和对象两种,事实上官方定义routes是一个数组;所以我们记住了,routes表示多个数组的集合;
router:译为路由器,上面都是路由,这个是路由器,我们可以理解为一个容器包含上述两个或者说它是一个管理者,负责管理上述两个;举个常见的场景的例子:当用户在页面上点击按钮的时候,这个时候router就会去routes中去查找route,就是说路由器会去路由集合中找对应的路由。
1.创建项目
安装好项目后,项目目录如下:
2.安装路由
打开项目下 package.json文件,查看 vue 版本。
vue 版本为 2.x,建议 vue-router 安装 3.x 版本。
vue 版本为 3.x,建议 vue-router 安装 4.x 版本。
随后在该项目目录下输入命令
npm install vue-router@版本号
3.创建文件
打开 src 文件夹,创建以下几个文件(有的默认创建好了)
该文件为默认创建文件,为了演示方便删除多余代码
<template>
<div class="hello">
<h2>HelloWorld</h2>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h4 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
<template>
<div>
<h3>Test</h3>
</div>
</template>
<script>
// 导出
export default {
name: 'TestItem'
}
</script>
<style>
</style>
// 引入vue
import Vue from 'vue';
// 引入vue-router
import VueRouter from 'vue-router';
// 注册 第三方库需要use一下才能用
Vue.use(VueRouter)
// 引入HelloWorld页面
import HelloWorld from '../components/HelloWorld.vue'
// 引入Test页面
import Test from '../components/Test.vue'
// 定义routes路由的集合,数组类型
const routes=[
//单个路由均为对象类型,path代表的是路径,component代表组件
{path:'/hw',component:HelloWorld},
{path:"/test",component:Test}
]
// 实例化VueRouter并将routes添加进去
const router = new VueRouter({
// ES6简写,等于routes:routes
routes
});
// 抛出这个这个实例对象方便外部读取以及访问
export default router
import Vue from 'vue'
import App from './App.vue'
import router from './router/index.js'
// 阻止vue在启动时生成的生产提示
Vue.config.productionTip = false
new Vue({
router: router,
render: h => h(App),
}).$mount('#app')
<template>
<div id="app">
<!--使用 router-link 组件进行导航 -->
<!--通过传递 `to` 来指定链接 -->
<!--`<router-link>` 将呈现一个带有正确 `href` 属性的 `<a>` 标签-->
<router-link to="/hw">HelloWorld</router-link>
<router-link to="/test">Test</router-link>
<hr>
<!-- 路由出口 -->
<!-- 路由匹配到的组件将渲染在这里 -->
<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.在项目文件下打开cmd,输入yarn serve
2.打开浏览器,访问 http://localhost:8080/
3.点击HelloWorld,页面无需刷新,跳转至http://localhost:8080/#/hw
4.点击Test,页面无需刷新,跳转至http://localhost:8080/#/test
到此,相信大家对“vue Router路由如何使用”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。