1. 程式人生 > 實用技巧 >洛谷 P4568 [JLOI2011]飛行路線

洛谷 P4568 [JLOI2011]飛行路線

Vue的封裝

封裝的意義

  • 提到程式碼的可讀性

  • 提⾼程式碼的可維護性

  • 減少程式碼的書寫

封裝

// src/api/http.js

import axios from 'axios'
axios.defaults.baseURL = "http://127.0.0.1:8000/"
// axios.defaults.baseURL = "http://172.16.240.175/:8000/"

//全域性設定⽹絡超時
axios.defaults.timeout = 10000;

//設定請求頭資訊
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.headers.put[
'Content-Type'] = 'application/json'; axios.interceptors.request.use( config => { // 每次傳送請求之前判斷是否存在token,如果存在,則統⼀在http請求的header都加上token,不⽤每次請求都⼿動添加了 const token = localStorage.getItem("token") // console.log(token) if (token) { config.headers.Authorization
= 'JWT ' + token } return config; }, error => { return Promise.error(error); }) axios.interceptors.response.use( // 請求成功 // res => res.status === 200 ? Promise.resolve(res) : Promise.reject(res), res => { if (res){ //加上201的原因是因為:modelviewset的post請求新增成功後返回的狀態碼是201
if(res.status === 200 || res.status === 201){ return Promise.resolve(res); } } } // 請求失敗 error => { if (error.response) { // 判斷⼀下返回結果的status == 401? ==401跳轉登入⻚⾯。 !=401passs // console.log(error.response) if (error.response.status === 401) { // 跳轉不可以使⽤this.$router.push⽅法、 // this.$router.push({path:'/login'}) window.location.href = "http://127.0.0.1:8888/" } else { // errorHandle(response.status, response.data.message); return Promise.reject(error.response); } // 請求已發出,但是不在2xx的範圍 } else { // 處理斷⽹的情況 // eg:請求超時或斷⽹時,更新state的network狀態 // network狀態在app.vue中控制著⼀個全域性的斷⽹提示元件的顯示隱藏 // 關於斷⽹元件中的重新整理重新獲取資料,會在斷⽹元件中說明 // store.commit('changeNetwork', false); return Promise.reject(error.response); } });

// 封裝xiaos請求 // 封裝get請求 export function axios_get(url, params) { return new Promise( (resolve, reject) => { axios.get(url, { params: params }) .then(res => { // console.log("封裝資訊的的res", res) resolve(res.data) }).catch(err => { reject(err.data) }) } ) }

// 封裝post請求 export function axios_post(url, data) { return new Promise( (resolve, reject) => { // console.log(data) axios.post(url, JSON.stringify(data)) .then(res => { // console.log("封裝資訊的的res", res) resolve(res.data) }).catch(err => { reject(err.data) }) } ) }

// 封裝put請求 export function axios_put(url, data) { return new Promise( (resolve, reject) => { // console.log(data) axios.put(url, JSON.stringify(data)) .then(res => { // console.log("封裝資訊的的res", res) resolve(res.data) }).catch(err => { reject(err.data) }) } ) }

// 封裝delete請求 export function axios_delete(url, data) { return new Promise( (resolve, reject) => { // console.log(data) axios.delete(url, { params: data }) .then(res => { // console.log("封裝資訊的的res", res) resolve(res.data) }).catch(err => { reject(err.data) }) } ) } export default axios; //⼀定要匯出函式

使⽤

// src/api/http.js

//將我們http.js中封裝好的 get,post.put,delete 導過來
import { axios_get, axios_post, axios_delete, axios_put } from './http.js'

export const qn_token_get = p => axios_get("/oauth/qntoken/", p) // 獲取七⽜雲
token
export const section_add = p => axios_post("/course/section/", p) // 獲取七⽜雲
token

// src/components/qiniu.vue
<script>
//導⼊axios函式 
import {qn_token_get,section_add} from './axios_api/api'
methods: {
     changeFile(e){
     // 獲取⽂件
         this.file = e.target.files[0];
     },
     gettoken(){
         //直接使⽤導⼊的axios函式
         qn_token_get().then(res=>{
 
             return this.token = res.data.uptoken
             console.log(this.token)
             })
         },
    }
</script>

跨域請求

瀏覽器的同源策略:⾮同源的⻚⾯之間,⽆法獲取資料

同源⼀般只⼀下三個東⻄相同:

  • 協議相同

  • 域名相同

  • 端⼝相同

同源策略的⽬的:是為了保證⽤戶資訊的安全,防⽌惡意的⽹站竊取資料。

同源策略的解決辦法:

  • jsonp

  • CORS

  • 代理解決跨域

vue元件間通訊

  • ⽗元件

<template>
     <div>
         <!-- 展示⼦元件的內容 -->
         <!-- :後的時⼦元件⾥⾯接收的名字,=後⾯的是⽗元件的名字 -->
         <!-- @後⾯的是⼦元件⾥定義的名字,=是⽗元件⾥獲取引數的名字 -->
         <zi :str="str" @change_fu="getzi" ></zi> 
         <button @click="change_zi()">修改⼦元件的資料</button>
         {{data}}
         <!-- {{str}} -->
     </div>
</template>

<script>
import zi from './zi1'
export default {
     name:"fu1.vue",
     components:{zi},
    data() {
         return {
             str:'',
             data:{}
         }
     },
     methods:{
         change_zi(){
             this.str = "⽼⼦讓你,你就得⼲啥,誰讓我是你爸爸"

         },
         getzi(val){
             console.log(val)
             this.data = val

         }
     }
}
</script>

⼦元件

<template>
     <div>
         <li>
             <ul>fghajkndlkajdakjd,⼤家上課⽅便那⽔庫⾥,減法計算</ul>
             {{str}}
             <button @click="send_fu()">把資料傳遞給⽗元件</button>
         </li>


     </div>
</template>

<script>
export default {
    name:"zi1",
    props:["str"],
    data() {
        return {
            data:{"name":"PP"}
       }  
    },

    methods:{
        send_fu(){
            console.log(this.data)
            this.$emit("change_fu",this.data)
        }
    }
}
</script>     

⽗⼦元件的調⽤:

  • Import 導⼊⼦元件

  • compants註冊⼦元件

  • 註冊的⼦元件當做標籤來使⽤

父元件給子元件傳參:

  • ⽗元件⾥的⼦標籤⾥寫上要傳遞的資料 (:⼦元件的引數名字=⽗元件的引數名字)

  • 在⼦元件⾥註冊引數(pros)

  • 使⽤⽗元件傳過來的引數

子元件給父元件傳參:

  • ⼦元件⾥先⽤特定的⽅法來把資料傳遞給⽗元件( this.$emit("⽅法的名字",要傳遞的資料))

  • ⽗元件的⼦標籤⾥來接收資料(@⼦元件的⽅法 = ⽗元件的⽅法)

  • 在methods⾥接收傳過來的val並賦值。