路由的使用

1.安裝 vue-router npm i vue-routerphp

2.src目錄下建立一個router目錄, 裏面建立一個index.js文件 , 這個目錄就是router的模塊vue

3.引入第三方的依賴包, 並註冊路由:ios

import Vue from 'vue'ajax

import VueRouter from 'vue-router'vue-router

Vue.use( VueRouter ) //使用vue-router這個第三方插件npm

注意: import這個關鍵字要放在整個文件的上層編程

const routes = [ axios

{api

path: '/home',跨域

component: Home

}//每個對象就是一個路由

]

const router = new VueRouter({

routes//路由表 必寫的

})

export default router

4.入口文件main.js中引入路由實例 router , 而後在根實例中註冊:

import router from './router/index.js'

new Vue({

router,

render: (h) => App

}).$mount('#app')

5.給路由一個路由展現區域

1.  若是是以及路由, 那麼咱們放在App組件中,用一個 <router-view > </router-view > 的組件表示

6.當頁面第一次的打開的時候, 須要作一個重定向, 就是要自動跳轉到 /home 這個 路由上:

const routes = [

{ //咱們要求這個路由的配置要放在路由表的最上方

path: '/',

redirect: '/home'

}

]

7.業務: 錯誤路由匹配:

const routes = [

{

path: '/',

redirect: '/home' //重定向

},

{

path: '/error',

component: Error

},

{ //這個就是錯誤路由匹配, vue規定這個必須放在最下面,它必須將上面的路由全找一遍,找不到才用當前這個

path: '**',

redirect: '/error'

}

]

mode:"history"

8.若是你使用 history , 那麼咱們最好將a標籤改爲 router-link 這個組件

·  router-link 這個組件 身上必需要有一個 to 屬性:

·  <router-link to='組件的名稱'></router-link>

·  router-link 這個組件身上加一個 keep-alive屬性能夠進行瀏覽器緩存

9.二級路由:

const routes = [

{

path: '/shopcar',

component: Shopcar,

children: [

{

path: 'yyb', // 不寫 /

component: Yyb

}

]

}

]

vue-router 進階 【 分類 -》 列表 -》 詳情 】

動態路由 & 路由傳參 & 路由接參

1.vue cli3 配置反向代理

在根目錄下面新建一個 vue.config.js

module.exports={

devServer: {

proxy: {

'/index.php': { // /index.php 是一個標記

target: 'http://www.qinqin.net', // 目標源

changeOrigin: true // 修改源

},

}

}

}

2.在列表頁面跨域獲取數據:

1.先安裝:npm i axios -S

<router-link

v-for='e in item.list' :key="e.api_cid" tag='li'

:to="{

name:'index',//須要跳轉的詳情頁面

params:{id:e.api_cid},

query:{

r:'class/cyajaxsub',

cid:e.api_cid,

}}">

<img :src="e.img">

<span>{{e.name}}</span>

</router-link>

<script>

import axios from 'axios'

export default {

data(){

return{

list:[]

}

},

created(){

axios({

url:'/index.php',

params:{

r: "class/category",

type: 1

}

}).then(res=>{this.list=res.data.data.data})

}

}

</script>

3.在詳情頁面跨域獲取數據:

<script>

import axios from 'axios'

export default {

data(){

return{

list:[]

}

},

created(){

axios({

url:'/index.php', //網站詳情頁的標識符

params:{ //網站詳情頁的參數

r: this.$route.query.r,//列表頁傳過來的r

page: 1,

cid: this.$route.query.cid,//列表頁傳過來的cid

px: 't',

cac_id: ''

}

}).then(res=>{this.list=res.data.data.content}

)

}

}

</script>

編程式導航

·  push

·  this.$router.push('/home') 

·  this.$router.push({name,params,query})

·  push能夠將咱們的操做存放到瀏覽器的歷史記錄

·  replace

·  this.$router.replace('/home')

·  this.$router.replace({name,params,query})

·  replace沒有將咱們的操做存放到瀏覽器的歷史記錄, 效果爲返回了二級

·  push/replace的參數就是to屬性的參數

 

相關文章
相關標籤/搜索