vue小項目總結與筆記【二】——vue的單文件組件模板和路由


 

 

vue的單文件組件的基本構成是這樣的:

<template>
    <div>
       結構: (注意:template里只能有一層div,不能出現兩個並列的div )
    </div>
</template>

// 邏輯 <script> export default { name: '組件名' } </script>
// css樣式 <style lang=""> </style>

 

項目打包完成后,可以看到main.js里有這樣的一段:


new Vue({ el: '#app', router, store, components: { App }, template: '<App/>' })

也就是說,項目的根實例為 <div id="app"></div>

再看App.vue文件:

<template>
  <div id="app">
      <router-view/>
  </div>
</template>

<script>
export default { name: 'App' } </script> <style> </style>

這里的router-view顯示的是當前路由的地址所對應的內容

如果去掉router-view,頁面就是空白的

 

那,路由(router)是什么?

字面意思是,根據網址的不同,返回不同的內容給用戶,例如,訪問根路徑‘/’,就訪問主頁,訪問‘/list’,那就訪問列表頁

 
 
路由的配置都放在router文件夾下的index.js文件里:
export default new Router({
  routes: [{
   // 當用戶訪問根路徑‘/’的時候,展現給用戶的是Home這個組件 path:
'/', name: 'Home', component: Home }, {
    //
當用戶訪問根路徑‘/city’的時候,展現給用戶的是City這個組件
    path: '/city',
    name:
'City',
    component: City }]

 當你創建一個新組件,需要進行路由配置的時候,在routes里面添加就好了:

 

export default new Router({
  routes: [{
    // 當用戶訪問根路徑‘/’的時候,展現給用戶的是Home這個組件
      path: '/',
      name: 'Home',
      component: Home
    }, {
    // 當用戶訪問根路徑‘/city’的時候,展現給用戶的是City這個組件
    path: '/city',
    name: 'City',
    component: City 
    }, {
    // 
    path: '/detail',    // 路徑
    name: 'Detail',    // 路由名
    component: Detail  //組件名
    }]

 

並在上面import引入 就可以了

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM