接 上篇文章,进行简单的页面间跳转
项目目录结构及说明
项目的目录结构图如下,未展开的文件夹表示未修改
新增文件情况
- 在src下新建router文件夹,随后在该文件夹下新建js文件index.js;
- 在components文件夹下新建vue文件Home.vue;
资源下载说明
- vue-router
- element-ui
步骤及代码
-
按照上方新增文件情况新建相应文件,名称可变
-
通过在Terminal终端输入命令引入所需的依赖(也可直接跳过此步在文件中import后根据提示安装)
-
vue-router
npm install vue-router --save
-
element-ui
npm i element-ui -S
完成后打开package.json文件查看,若出现相应依赖及其版本则安装成功
-
-
main.js
import Vue from 'vue' import App from './App.vue' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' import router from './router' Vue.config.productionTip = false Vue.use(ElementUI) new Vue({ router, render: h => h(App), }).$mount('#app')
-
App.vue
App.vue中原本是以直接插入组件的方式加载,现将其改为使用路由视图(router-view)的方式。<template> <div id="app"> <img alt="Vue logo" src="./assets/logo.png"> <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>
-
router/index.js
该文件用于定义url路径及要使用的组件,使用history模式免去路径中的#import Vue from 'vue' import VueRouter from 'vue-router' import HelloWorld from "../components/HelloWorld"; import Home from "@/components/Home"; Vue.use(VueRouter) const routes = [ { path: '/', name: 'HelloWorld', component: HelloWorld }, { path: '/home', name: 'Home', component: Home, }, ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router
-
HelloWorld.vue
该文件将原先的代码简化并添加一个按钮,以实现点击跳转到新页面的功能,可根据需要对按钮属性进行设置<template> <div class="hello"> <h1>hello, world</h1> <el-button class="button1" type="primary" @click="tiaoZhuan()">点击回家</el-button> </div> </template> <script> export default { name: 'HelloWorld', methods: { tiaoZhuan(){ this.$router.push('/home') this.$message({ showClose: true, message: 'Welcome', type: 'success' }); } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
-
Home.vue
该组件实现一个简单的页面,只有一行文字<template> <div> <h1>Welcome to Home!</h1> </div> </template> <script> export default { name: "Home" } </script> <style scoped> </style>
运行
点击运行,打开浏览器访问网址http://localhost:8080/
点击按钮进行跳转,可以看到路径发生改变,跳转成功
芜湖,完毕!