(八)vue組件通訊和路由

4:組件通訊的5種方式vue

    propsios

    vue的自定義事件ajax

    pubsub第三方庫vue-router

    slotvuex

    vuexnpm

    props:axios

        父子組件間通訊的基本方式緩存

        屬性值的2大類型:函數

            通常: 父組件-->子組件vue-resource

            函數: 子組件-->父組件

                 隔層組件間傳遞: 必須逐層傳遞(麻煩)

                 兄弟組件間: 必須藉助父組件(麻煩)

        vue自定義事件

            子組件與父組件的通訊方式

            用來取代function props

            不適合隔層組件和兄弟組件間的通訊

        pubsub第三方庫(消息訂閱與發佈)

            適合於任何關係的組件間通訊

        slot

            通訊是帶數據的標籤

            注意: 標籤是在父組件中解析

        vuex

            多組件共享狀態(數據的管理)

            組件間的關係也沒有限制

            功能比pubsub強大, 更適用於vue項目

5:ajax請求

(1)vue-resource

npm install vue-resource –save

// 引入模塊

import VueResource from 'vue-resource'

// 使用插件

Vue.use(VueResource)

// 經過 vue/組件對象發送 ajax 請求

this.$http.get('/someUrl').then((response) => {

// success callback

console.log(response.data) //返回結果數據

}, (response) => {

// error callback}

 

(2)axios

npm install axios –save

// 引入模塊

import axios from 'axios'

// 發送 ajax 請求

axios.get(url)

.then(response => {

console.log(response.data) // 獲得返回結果數據

})

.catch(error => {

console.log(error.message)

})

 

6:vue-router

1:路由:(1)定義路由組件 (2)配置路由 (3)引入路由

     組件 拆分組件,編寫靜態組件,動態組件

定義路由組件:(1)註冊路由(2)使用路由  <router-link>  <router-view>

 

路由組件:News.vue   Message.vue 

配置路由:

path: '/home',

component: home,

children: [

{

path: 'news',

component: News

},

{

path: 'message',

component: Message

}

]

使用路由  <router-link to="/home/news">News</router-link>

<router-link to="/home/message">Message</router-link>

<router-view></route-view>

 

2:路由組件傳遞數據

(1)       路由路徑攜帶參數(param/query)

配置路由

children: [{path: 'mdetail/:id', component: MessageDetail }]

路由路徑:<router-link :to="'/home/message/mdetail/'+m.id">{{m.title}}</router-link>

路由組件中讀取請求參數 this.$route.params.id

<router-link :to="`/home/message/detail/${message.id}`"> {{message.title}}</router-link>

(2)緩存路由對象

<keep-alive>

<router-view></router-view>

</keep-alive>

//路由歷史記錄

(1) this.$router.push(path): 至關於點擊路由連接(能夠返回到當前路由界面)

(2) this.$router.replace(path): 用新路由替換當前路由(不能夠返回到當前路由界面)

(3) this.$router.back(): 請求(返回)上一個記錄路由

(4) this.$router.go(-1): 請求(返回)上一個記錄路由

(5) this.$router.go(1): 請求下一個記錄路由

相關文章
相關標籤/搜索