vue-router路由
导入vue-router
Vue Router v3对应Vue2.x, v4对应Vue3,
yarn add vue-router@3.2.0
使用上面的npm代码,可以自动匹配适合当前vue的vue-router
在src下创建components目录
该目录下都写组件,新建一个VUE文件
<template> <h1>内容页</h1> </template> <script> export default { name: "content" } </script> <style scoped> /*scoped作用域,这个style只在当前模板生效*/ </style>
当然可以创建多个VUE文件
配置router
在src下新建一个router目录,再新建一个index.js文件(主要配置文件都放在index.js中)
编写index.js
//导入主要的Vue import Vue from 'vue' import VueRouter from 'vue-router' //导入组件 import content from "../components/comtent"; import Main from '../components/Main' import king from '../components/king' //使用router Vue.use(VueRouter); //导出router export default new VueRouter({ //配置路由 routes: [ { //配置路由路径 path: '/content', //跳转的组件 component: content }, { //配置路由路径 path: '/Main', //跳转的组件 component: Main }, { //配置路由路径 path: '/king', //跳转的组件 component: king } ] })
这里会导出路由,以便在main.js中配置
配置main.js
import Vue from 'vue' import App from './App' import router from './router' //由于配置文件是index.js,vue会自动扫描 Vue.config.productionTip = false Vue.use(router) new Vue({ el: '#app', //在主入口配置路由 router, components: { App }, template: '<App/>' })
转到App.vue中配置
<template> <div id="app"> <!-- 跳转视图 --> <router-link to="/Main">首页</router-link> <router-link to="/content">内容页</router-link> <router-link to="/king">king</router-link> <!--展示视图--> <router-view></router-view> </div> </template> <script> //引用组件 //1.使用import xx from(组件的地址) //2.引用组件 /*components:{ comtent }*/ 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>
在终端输入命令
npm run dev
启动项目
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决