單頁面,顧名思義,就是整個項目只有一個頁面,但是可以展示不同的內容。那在vue中它是如何實現單頁面的?
我先畫一下它的流程路線,index.html----main.js---app.vue---router.js----xxx.vue,接下來我們具體跑一下這條路線。
1. 項目構建成功后,在public目錄下有個index.html,這個頁面就是整個項目唯一的頁面,也是瀏覽器訪問的唯一頁面,我們先看一下它里面的內容:
<!--瀏覽器訪問的唯一頁面(單頁面應用SPA)--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <link rel="icon" href="<%= BASE_URL %>favicon.ico"> <title><%= htmlWebpackPlugin.options.title %></title> </head> <body style="margin: 0px; padding: 0px"> <!--如果瀏覽器不支持scrip時,就展示這段話--> <noscript> <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <!--這個APP被main.js里面的APP所代替--> <div id="app"></div> <!-- built files will be auto injected --> </body> </html>
2. 其中核心就是 <div id="app"></div>,頁面所有內容都在這個div中,那如何將內容放到這div中的呢?接下來就要引入main.js,也就是項目的唯一入口,我們先看一下它里面的內容:
/*項目的唯一入口,相當於main函數*/ import Vue from 'vue' /*引入app.vue組件*/ import App from './App.vue' import router from './router' new Vue({ router, store, /* APP就是要渲染的組件*/ render: h => h(App) /* $mount('#app'):掛載到#APP這里(index。HTML里面)*/ }).$mount('#app')
srender: h => h(App),是要渲染的APP.vue組件,
$mount('#app')是將app.vue組件掛載到index.html中
3.main.js相當於的中間件,用於連接index.html和app.vue,那么app.vue又是什么,接下來我們先看一下它里面的內容:
<template> <div id="app"> <!-- <router-view/>相當於占位符,它對應到router里面的index。js 當你的請求路徑是哪個,它對應的就是哪個組件也就是哪個。vue文件--> <router-view/> </div> </template>
4.里面這個div就是main.js中 import App from './App.vue'。main.js所渲染的也是就是這個div中的內容,但div中只有<router-view/>,那么他是什么意思呢?通俗一點來說,他就是一個占位符,它對應到router里面的index.js當你的請求路徑是哪個,它對應的就是哪個組件,也就是哪個.vue文件,也就會展示不同的內容。那么router里面的index.js里面又有什么內容呢?
import Vue from 'vue'
import VueRouter from 'vue-router'
import Test1 from '../views/Test1.vue'
import Test2 from '../views/Test2.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/test1',
name: '一',
component: Test1
} ,
{
path: '/test2',
name: '二',
component: Test2
}
]
const router = new VueRouter({
routes
})
export default router
5.從代碼可以看出,當我們在瀏覽的請求路徑是 index.html/test1 時,就會加載Test1.vue這個組件,也就會展示它里面的內容。同樣的,請求路徑是 index.html/test2 時,就會加載Test2.vue這個組件.
那么Test1.vue這個組件里面的內容應該怎么寫呢,其實很簡單,我們先看一下:
<template> <div>test1</div> </template> <script> export default { name: "Test1", /* data 用於定義屬性*/ /*用return的意思是只在當前組件有效 不使用return包裹的數據會在項目的全局可見,會造成變量污染 使用return包裹后數據中變量只在當前組件中生效,不會影響其他組件 * */ data() { return {
} }, /* methods 用於定義的函數,可以通過 return 來返回函數值。*/ methods: { } } </script> <style scoped> </style>
<!--組件的定義用.vue文件
包含三部分:template:定義HTML元素
script:定義點擊事件,數據的動態處理
style:定義樣式-->
至此,一個完整的線路就算走完了,是不是有點繞,感覺一層一層的,我們再來梳理一下。這次,我們反着來:
xx.vue組件--------router里面的index.html,引入.vue文件,並定義他們的請求路徑。--------------app.vue,將<router-view/>替換成我們請求
路徑的那個xx.vue組件------------main.js中引入app.vue,渲染它,並把他掛載到
index.html中-------------index.html,瀏覽器訪問。