6-1.Vue-router安裝和簡單的應用

Vue-router

在vue應用中,使用a標籤進行頁面的鏈接是無法起作用的,這時需要採用vue-router插件(Vue開發中由於對路由的不支持,需採用vue-router插件);
學習vue,必須知道路由的作用。路由就是SPA(單頁應用)的路徑管理器,vue-router是一個WebApp的鏈接路徑管理系統,由於Vue開發的都是單頁面應用,只有一個index.html主頁面,所以需要採用該插件來管理。

vue-router安裝

1.在搭建Vue的腳手架vue-cli時如果已經確認安裝vue-router插件,則無需重複安裝。如果選擇“Y”則在初始化項目時就已經安裝好了。

Install vue-router? Y

2.若在搭建腳手架時沒有安裝vue-router插件,則在命令行工具使用以下命令進行安裝:

npm install vue-router --save-dev

index.js文件的重要解讀

import Vue from 'vue'   //引入Vue
import Router from 'vue-router'  //引入vue-router
import Hello from '@/components/Hello'  //引入根目錄下的Hello.vue組件

Vue.use(Router)  //Vue全局使用Router

export default new Router({
  routes: [              //配置路由,這裏是個數組
    {                    //每一個鏈接都是一個對象
      path: '/',         //鏈接路徑
      name: 'Hello',     //路由名稱,
      component: Hello   //對應的組件模板
    }
  ]
})

注意:
1.import語句將引入Vue應用 , vue-router插件以及其他組件
2.routers配置路由,其後接的是一個數組(鏈接數組)
3.數組裏面存放的是每一個鏈接對象,包含了path ,name,component參數

添加新的模板頁面

1.在src/components目錄下新建vue文件,(demo.vue文件)
2.編寫文件內容,文件主要包括三個部分:<template><script>和<style>
3.在template標籤裏面添加想要顯示的內容,這裏顯示Hi,This is my first rounter

<script>
	export default{
		data(){
			return{
				content:'Hi,This is my first rounter'
			}
		}
	}
</script>

4.在index.js進行路由配置

  • 引入demo組件:在router/index.js文件的上邊引入Hi組件
import demo from '@/components/demo'
  • 增加路由配置:在router/index.js文件的routes[]數組中,新增加一個對象
export default new Router({
  routes: [
	{
		path:'/demo',
		name:'Demo',
		compontent:Demo
	}
  ]
})

完成之後,在瀏覽器輸入http://localhost:8080/#/demo
在這裏插入圖片描述
附加:
利用<router-link>可以製作導航,可以鏈接到其他頁面。

 <router-link to="/">[顯示字段]</router-link>
  • to後面接的是導航的路徑
  • [顯示字段] :就是導航名稱,比如首頁。
    在App.vue頁面添加導航鏈接,實現導航
<template>
  <div id="app">
    <img src="./assets/logo.png">
	<div>
		導航
		<p>
			<router-link to="/demo">跳轉到demo頁面</router-link>
		</p>
		<p>
			<router-link to="/">跳轉到首頁面</router-link>
		</p>
	</div>
    <router-view/>
	
  </div>
</template>

在這裏插入圖片描述
這樣就實現了用<router-link>標籤設置導航,點擊就可以實現頁面內容的變化。

發佈了54 篇原創文章 · 獲贊 12 · 訪問量 3369
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章