一、安裝router
Terminal中運(yùn)行以下代碼自動(dòng)安裝
npm install vue-router --save
安裝完成后,在package.json中查看vue-router是否安裝成功
"dependencies": {
"axios": "^0.27.2",
"core-js": "^3.8.3",
"vue": "^3.2.13",
"vue-router": "^4.1.3" //vue-router安裝成功,版本是^4.1.3
},
二、配置router文件
src目錄下新建一個(gè)router文件夾,在router文件夾里新建一個(gè)index.js文件,index.js中的代碼如下
import { createRouter,createWebHistory} from 'vue-router';
const router = createRouter({
routes: [
{
path: '/home',
//路由到的地址(自定義)
component:()=>import('../components/Home.vue'),
//引入組件,組件Home.vue所在路徑
//Home.vue是需要路由的vue組件
name: 'Home'
//組件名稱
},
],
history: createWebHistory()
})
export default router;
三、在main.js中引用index.js
main.js中代碼如下
import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index.js';
const app = createApp(App)
app.use(router)
app.mount('#app')
//此處也是vue3與vue2的區(qū)別之處
四、以上三步完成了router的安裝和配置,接下來是使用
在主頁(yè)面App.vue中的模板內(nèi)寫入一下兩行代碼即可
<router-link to="/home">Home</router-link>
// to="/home" 這個(gè)地址就是index.js中的path
<router-view></router-view>
// 必須要加,不然Home.vue的內(nèi)容無法顯示
五、 完成效果
運(yùn)行項(xiàng)目,打開運(yùn)行地址,此時(shí)是App.vue的界面
點(diǎn)擊?Home,左上角地址路由至/home (也就是index.js中的path)
Home下方顯示了Home.vue界面的內(nèi)容
?文章來源地址http://www.zghlxwxcb.cn/news/detail-418342.html
?文章來源:http://www.zghlxwxcb.cn/news/detail-418342.html
?
到了這里,關(guān)于vue3:router安裝與使用的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!