1.安装环境,开发环境
1.1、node.js环境(nodejs.org/zh-cn/)
1.2、vscode开发工具(code.visualstudio.com/)
1.3、vscode安装Vue Language Features (Volar)插件,此插件是用于识别vue语法包。
1.4、安装vue_cli通过cmd命令执行”npm install -g @vue/cli“, vue_cli是一个快速搭建大型单页应用的脚手架,安装后可以通过cmd”vue --version“命令查询vue版本。
2.搭建项目
2.1、创建项目在cmd执行”vue create 项目名称“。创建成功后用vscode打开次项目目录。
2.2、安装vue路由在vscode项目终端执行”npm install vue-router@4“。
2.3、运行项目在vscode项目终端执行”npm run serve“。
2.4、项目打包在vscode项目终端执行“npm run build”。
3.vue路由用法
3.1创建一个router.js。
// 1 从vue-router按需导入两个方法
// createRouter方法用于创建路由实例对象
// createWebHashHistory方法用于指定路由的工作模式(hash模式)
import { createRouter, createWebHashHistory } from 'vue-router'
// 2 导入需要使用路由控制的组件
import HelloWorld from './components/HelloWorld.vue'
import Vuew from './components/Vuew.vue'
// 3 创建路由对象
const router = createRouter({
// 3.1 通过 history 属性,指定路由的工作模式
history: createWebHashHistory(),
// 3.2 通过 routes 数组,指定路由规则
// path 是 hash 地址,component 是要展示的组件
routes: [
{ path: '/home', component: HelloWorld },
{ path: '/movie', component: Vuew }
],
})
// 4、向外共享路由对象
export default router
3.2在man.js引用此文件
import { createApp } from 'vue'
import App from './App.vue'
// 导入路由模块
import router from './router'
//加载ant-design-vueui框架 https://2x.antdv.com/components/button-cn
import antd from 'ant-design-vue';
import 'ant-design-vue/dist/antd.css';
import axios from 'axios'
var app = createApp(App);
app.config.productionTip = false;
/* 挂载全局对象 start */
// 配置请求的跟路径
axios.defaults.baseURL = 'http://127.0.0.1'
app.config.globalProperties.$http = axios;
// 挂载路由模块
app.use(router);
// 挂载ant-design模块
app.use(antd);
app.mount('#app');
3.3在App.vue更改代码如下
<template>
<div>
<router-view></router-view>
</div>
</template>
<script>
</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>
3.4页面实现跳转
<router-link to="/home">首页</router-link>
//js跳转路由
this.$router.push('/home')
this.$router.push({path:'/home'})
#query 传参,相当于get请求,
this.$router.push({ path:'/user',query:{ id:this.id}})
# params 传参,相当于post请求
this.$router.push({ path:'/user',params:{id:this.id}})
// 接收参数
this.$route.params.id
#相对于当前页面向前或向后跳转多少个页面,类似 window.history.go(n)。n可为正数可为负数。正数返回上一个页面。
this.$router.go(1)
#前进一步
this.router.forward()
#回退一步
this.router.back()