欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue中的Ajax?配置代理slot插槽的方法詳解

 更新時(shí)間:2023年06月16日 11:52:08   作者:懷夢(mèng)  
這篇文章主要介紹了Vue中的Ajax?配置代理?slot插槽的相關(guān)知識(shí),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

4.1.Vue腳手架配置代理

本案例需要下載axios庫(kù)npm install axios

配置參考文檔Vue-Cli devServer.proxy

vue.config.js 是一個(gè)可選的配置文件,如果項(xiàng)目的 (和 package.json 同級(jí)的) 根目錄中存在這個(gè)文件,那么它會(huì)被 @vue/cli-service 自動(dòng)加載。你也可以使用 package.json 中的 vue 字段,但是注意這種寫法需要你嚴(yán)格遵照 **JSON **的格式來(lái)寫

4.1.1.方法一

vue.config.js中添加如下配置

module.exports = { 
devServer : { 
  proxy:"http://localhost:5000" 
  } 
}

說明

  • 優(yōu)點(diǎn):配置簡(jiǎn)單,請(qǐng)求資源時(shí)直接發(fā)給前端(8080)即可
  • 缺點(diǎn):不能配置多個(gè)代理,不能靈活的控制請(qǐng)求是否走代理
  • 工作方式:若按照上述配置代理,當(dāng)請(qǐng)求了前端不存在的資源時(shí),才會(huì)將請(qǐng)求會(huì)轉(zhuǎn)發(fā)給服務(wù)器 (優(yōu)先匹配前端資源)

4.1.2.方法二

編寫vue.config.js配置具體代理規(guī)則

module.exports = {
  devServer: {
    proxy: {
      '/api1': {                            // 匹配所有以 '/api1'開頭的請(qǐng)求路徑
        target: 'http://localhost:5000',    // 代理目標(biāo)的基礎(chǔ)路徑
        pathRewrite: {'^/api1':''},         // 代理往后端服務(wù)器的請(qǐng)求去掉 /api1 前綴
        ws: true,                           // 用于支持websocket,默認(rèn)值為true
        changeOrigin: true                  // 用于控制請(qǐng)求頭中的host值,默認(rèn)值為true 
      },
      '/api2': {
        target: 'http://localhost:5001',
        pathRewrite: {'^/api2': ''},
        changeOrigin: true
      }
    }
  }
}
/**
 * changeOrigin設(shè)置為true時(shí),服務(wù)器收到的請(qǐng)求頭中的host為:localhost:5000
 * changeOrigin設(shè)置為false時(shí),服務(wù)器收到的請(qǐng)求頭中的host為:localhost:8080
 * changeOrigin默認(rèn)值為true
 */

說明

  • 優(yōu)點(diǎn):可以配置多個(gè)代理,且可以靈活的控制請(qǐng)求是否走代理
  • 缺點(diǎn):配置略微繁瑣,請(qǐng)求資源時(shí)必須加前綴

vue.config.js

const { defineConfig } = require('@vue/cli-service')
module.exports = {
  pages: {
    index: {
      // page 的入口
      entry: './src/main.js'
    }
  },
  // 關(guān)閉語(yǔ)法檢查
  lintOnSave: false,
  // 開啟代理服務(wù)器 (方式一)
  // devServer: { 
  //   proxy:"http://localhost:5000" 
  // }
  // 開啟代理服務(wù)器 (方式二)
  devServer: {
    proxy: {
      '/api1': {
        target: 'http://localhost:5000',
        pathRewrite: {
          '^/api1': ''
        }
        // ws: true, //用于支持websocket,默認(rèn)值為true
        // changeOrigin: true //用于控制請(qǐng)求頭中的host值,默認(rèn)值為true , 
      },
      '/api2': {
        target: 'http://localhost:5001',
        pathRewrite: {
          '^/api2': ''
        },
      }
    }
  }
}

src/App.vue

<template>
    <div>
        <button @click="getStudents">獲取學(xué)生信息</button>
    </div>
</template> 
<script> 
    // 引入組件
    import axios from 'axios';
    export default { 
        name:'App',
        methods: {
            getStudents() {
                axios.get('http://localhost:8080/api1/students').then(
                    response => { 
                        console.log('請(qǐng)求成功了',response.data);
                    },
                    error => { 
                        console.log('請(qǐng)求失敗了',error.message);
                    }
                )
            },
            getCars() {
                axios.get('http://localhost:8080/api2/cars').then(
                    response => { 
                        console.log('請(qǐng)求成功了',response.data); 
                    },
                    error => { 
                        console.log('請(qǐng)求失敗了',error.message); 
                    }
                );
            }
        }
    }
</script>

4.2.GitHub用戶搜索案例

public/index.html

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <!-- 針對(duì)IE游覽器的一個(gè)特殊配置,含義是讓IE游覽器以最高的渲染級(jí)別渲染頁(yè)面 -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- 開啟移動(dòng)端的理想視口 -->
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <!-- 配置頁(yè)簽圖標(biāo) -->
    <link rel="icon" href="<%= BASE_URL %>favicon.ico" rel="external nofollow" >
    <!-- 引入bootstrap樣式 --> 
    <link rel="stylesheet" href="<%= BASE_URL %>css/bootstrap.css" rel="external nofollow" >
    <!-- 配置網(wǎng)頁(yè)的標(biāo)題 -->
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>
  <body>
    <!-- 當(dāng)游覽器不支持js時(shí)noscript中的元素就會(huì)被渲染-->
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <!-- 容器 -->
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

src/main.js

import Vue from 'vue';
import App from './App.vue';
Vue.config.productionTip = false;
new Vue({
  el: '#app',
  render: h => h(App),
  beforeCreate() {
    Vue.prototype.$bus = this; // 安裝全局事件總線
  }
})

src/App.vue

<template>
    <div class="container">
        <Search/>
        <List/>
    </div>
</template> 
<script> 
    // 引入組件
    import Search from './components/Search.vue';
    import List from './components/List.vue';
    export default {
        name:'App',
        components:{
            Search,
            List
        },
    }
</script>

src/components/Search.vue

<template>
    <div class="container">
        <Search/>
        <List/>
    </div>
</template> 
<script> 
    // 引入組件
    import Search from './components/Search.vue';
    import List from './components/List.vue';
    export default {
        name:'App',
        components:{
            Search,
            List
        },
    }
</script>

src/components/List.vue

<template>
    <section class="jumbotron">
        <h3 class="jumbotron-heading">Search Github Users</h3>
        <div>
            <input type="text" placeholder="enter the name you search" v-model="keyWord"/>&nbsp;
            <button @click="searchUsers">Search</button>
        </div>
    </section>
</template>
<script>
    import axios from "axios";
    export default {
        name: "Search",
        data() {
            return {
                keyWord: ""
            };
        },
        methods: {
            searchUsers() {
                // 請(qǐng)求前更新List的數(shù)據(jù)
                this.$bus.$emit("updateListData", {
                    isLoading: true,
                    errMsg: "",
                    users: [],
                    isFirst: false,
                });
                axios.get(`https://api.github.com/search/users?q=${this.keyWord}`).then(
                    (response) => {
                        console.log("請(qǐng)求成功了");
                        // 請(qǐng)求成功后更新List的數(shù)據(jù)
                        this.$bus.$emit("updateListData", {
                            isLoading: false,
                            errMsg: "",
                            users: response.data.items
                        });
                    },
                    (error) => {
                        // 請(qǐng)求后更新List的數(shù)據(jù)
                        this.$bus.$emit("updateListData", {
                            isLoading: false,
                            errMsg: error.message,
                            users: []
                        });
                    }
                );
            }
        }
    }
</script>

4.3.vue-resource

vue項(xiàng)目常用的兩個(gè)Ajax庫(kù)

  • axios:通用的Ajax請(qǐng)求庫(kù),官方推薦,效率高
  • vue-resource:vue插件庫(kù),vue 1.x使用廣泛,官方已不維護(hù)

下載vue-resource庫(kù)npm i vue-resource

src/main.js

import Vue from 'vue';
import App from './App.vue';
import vueResource from 'vue-resource';
Vue.config.productionTip = false;
Vue.use(vueResource);
new Vue({
  el: '#app',
  render: h => h(App),
  beforeCreate() {
    Vue.prototype.$bus = this; // 安裝全局事件總線
  }
})

src/App.vue

<template>
    <div class="container">
        <Search/>
        <List/>
    </div>
</template> 
<script> 
    // 引入組件
    import Search from './components/Search.vue';
    import List from './components/List.vue';
    export default {
        name:'App',
        components:{
            Search,
            List
        },
    }
</script>

src/components/Search.vue

<template>
    <section class="jumbotron">
        <h3 class="jumbotron-heading">Search Github Users</h3>
        <div>
            <input type="text" placeholder="enter the name you search" v-model="keyWord"/>&nbsp;
            <button @click="searchUsers">Search</button>
        </div>
    </section>
</template>
<script>
    export default {
        name: "Search",
        data() {
            return {
                keyWord: ""
            };
        },
        methods: {
            searchUsers() {
                // 請(qǐng)求前更新List的數(shù)據(jù)
                this.$bus.$emit("updateListData", {
                    isLoading: true,
                    errMsg: "",
                    users: [],
                    isFirst: false,
                });
                this.$http.get(`https://api.github.com/search/users?q=${this.keyWord}`).then(
                    (response) => {
                        console.log("請(qǐng)求成功了");
                        // 請(qǐng)求成功后更新List的數(shù)據(jù)
                        this.$bus.$emit("updateListData", {
                            isLoading: false,
                            errMsg: "",
                            users: response.data.items
                        });
                    },
                    (error) => {
                        // 請(qǐng)求后更新List的數(shù)據(jù)
                        this.$bus.$emit("updateListData", {
                            isLoading: false,
                            errMsg: error.message,
                            users: []
                        });
                    }
                );
            }
        }
    }
</script>

src/components/List.vue

<template>
    <div class="row">
        <!-- 展示用戶列表 -->
        <div
                v-show="info.users.length"
                class="card"
                v-for="user in info.users"
                :key="user.login"
        >
            <a :href="user.html_url" rel="external nofollow"  target="_blank">
                <img :src="user.avatar_url" style="width: 100px" />
            </a>
            <p class="card-text">{{ user.login }}</p>
        </div>
        <!-- 展示歡迎詞 -->
        <h1 v-show="info.isFirst">歡迎使用!</h1>
        <!-- 展示加載中 -->
        <h1 v-show="info.isLoading">加載中....</h1>
        <!-- 展示錯(cuò)誤信息 -->
        <h1 v-show="info.errMsg">{{ info.errMsg }}</h1>
    </div>
</template>
<script>
    export default {
        name: "List",
        data() {
            return {
                info: {
                    isFirst: true,
                    isLoading: false,
                    errMsg: "",
                    users: [],
                }
            }
        },
        mounted() {
            this.$bus.$on("updateListData", (dataObj) => {
                    this.info = { ...this.info, ...dataObj };
                }
            );
        }
    }
</script>
<style scoped>
    album {
        min-height: 50rem; /* Can be removed; just added for demo purposes */
        padding-top: 3rem;
        padding-bottom: 3rem;
        background-color: #f7f7f7;
    }
    .card {
        float: left;
        width: 33.333%;
        padding: 0.75rem;
        margin-bottom: 2rem;
        border: 1px solid #efefef;
        text-align: center;
    }
    .card > img {
        margin-bottom: 0.75rem;
        border-radius: 100px;
    }
    .card-text {
        font-size: 85%;
    }
</style>

4.4.slot 插槽

<slot>插槽:讓父組件可以向子組件指定位置插入html結(jié)構(gòu),也是一種組件間通信的方式,適用于 父組件 ===> 子組件

  • 分類:默認(rèn)插槽、具名插槽、作用域插槽
  • 使用方式

1.默認(rèn)插槽

父組件中: 
  <Category> 
    <div>html結(jié)構(gòu)1</div> 
  </Category> 
子組件中:Category 
  <template> 
    <div> 
      <!-- 定義插槽 --> 
      <slot>插槽默認(rèn)內(nèi)容...</slot> 
    </div> 
  </template>

2.具名插槽,父組件指明放入子組件的哪個(gè)插槽slot=“footer”,如果是template可以寫成v-slot:footer

父組件中: 
  <Category> 
    <template slot="center"> 
      <div>html結(jié)構(gòu)1</div> 
    </template> 
    <template v-slot:footer>
      <div>html結(jié)構(gòu)2</div> 
    </template> 
  </Category>
子組件中: 
  <template> 
    <div> 
      <!-- 定義插槽 --> 
      <slot name="center">插槽默認(rèn)內(nèi)容...</slot> 
      <slot name="footer">插槽默認(rèn)內(nèi)容...</slot> 
    </div> 
  </template>

3.作用域插槽,scope用于父組件往子組件插槽放的html結(jié)構(gòu)接收子組件的數(shù)據(jù);理解:數(shù)據(jù)在組件的自身,但根據(jù)數(shù)據(jù)生成的結(jié)構(gòu)需要組件的使用者來(lái)決定(games數(shù)據(jù)在Category組件中,但使用數(shù)據(jù)所遍歷出來(lái)的結(jié)構(gòu)由App組件決定)

注意:關(guān)于樣式,既可以寫在父組件中,解析后放入子組件插槽;也可以放在子組件中,傳給子組件再解析

父組件中: 
  <Category> 
    <template scope="scopeData"> 
      <!-- 生成的是ul列表 --> 
      <ul> 
        <li v-for="g in scopeData.games" :key="g">{{g}}</li> 
      </ul> 
    </template>
  <Category> 
    <template slot-scope="scopeData"> 
    <!-- 生成的是h4標(biāo)題 --> 
    <h4 v-for="g in scopeData.games" :key="g">{{g}}</h4> 
    </template> 
  </Category>
子組件中:
  <template> 
    <div> 
      <slot :games="games"></slot> 
    </div> 
  </template>
  <script> 
    export default { 
      name:'Category', props:['title'], 
      //數(shù)據(jù)在子組件自身 
      data() { 
        return { 
          games:['紅色警戒','穿越火線','勁舞團(tuán)','超級(jí)瑪麗'] 
        } 
      },
    } 
  </script>

4.4.1.默認(rèn)插槽

src/App.vue

<template>
    <div class="container">
        <Category title="美食">
            <img src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg" alt="">
        </Category>
        <Category title="游戲">
            <ul>
                <li v-for="(item, index) in games" :key="index">{{item}}</li>
            </ul>
        </Category>
        <Category title="電影">
            <video controls src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"></video>
        </Category>
    </div>
</template> 
<script> 
    // 引入組件
    import Category from './components/Category.vue';
    export default {
        name:'App',
        components:{
            Category
        },
        data() {
            return {
                foods: ['火鍋','燒烤','小龍蝦','牛排'],
                games: ['紅色警戒','穿越火線','勁舞團(tuán)','超級(jí)瑪麗'],
                films:['《教父》','《拆彈專家》','《你好,李煥英》','《尚硅谷》']
            }
        }
    }
</script>
<style>
    .container {
        display: flex;justify-content: space-around;
    }
</style>

src/components/Category.vue

<template>
    <div class="category">
        <h3>{{title}}分類</h3>
        <!-- 定義一個(gè)插槽(挖個(gè)坑,等著組件的使用者進(jìn)行填充) -->
        <slot>我是一些默認(rèn)值,當(dāng)使用者沒有傳遞具體結(jié)構(gòu)時(shí),我會(huì)出現(xiàn)</slot>
    </div>
</template>
<script>
    export default {
        name: "Category",
        props:['title']
    }
</script>
<style scoped>
    .category {
        background-color: skyblue;
        width: 200px;
        height: 300px;
    }
    h3 {
        text-align: center;
        background-color: orange;
    }
    video {
        width: 100%;
    }
    img {
        width: 100%;
    }
</style>

4.4.2.具名插槽

src/App.vue

<template>
    <div class="container">
        <Category title="美食">
            <img slot="center" src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg" alt="" >
            <a slot="footer"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >更多美食</a>
        </Category>
        <Category title="游戲">
            <ul slot="center">
                <li v-for="(item, index) in games" :key="index">{{item}}</li>
            </ul>
            <div class="foot" slot="footer">
                <a  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >單機(jī)游戲</a> 
                <a  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >網(wǎng)絡(luò)游戲</a>
            </div>
        </Category>
        <Category title="電影">
            <video slot="center" controls src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"></video>
            <template v-slot:footer>
                <div class="foot">
                    <a  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >經(jīng)典</a> 
                    <a  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >熱門</a> 
                    <a  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >推薦</a>
                </div>
                <h4>歡迎前來(lái)觀影</h4>
            </template>
        </Category>
    </div>
</template> 
<script> 
    // 引入組件
    import Category from './components/Category.vue';
    export default {
        name:'App',
        components:{
            Category
        },
        data() {
            return {
                foods: ['火鍋','燒烤','小龍蝦','牛排'],
                games: ['紅色警戒','穿越火線','勁舞團(tuán)','超級(jí)瑪麗'],
                films:['《教父》','《拆彈專家》','《你好,李煥英》','《尚硅谷》']
            }
        }
    }
</script>
<style>
    .container,.foot {
        display: flex;justify-content: space-around;
    }
    h4{text-align: center;}
</style>

src/components/Category.vue

<template>
    <div class="category">
        <h3>{{title}}分類</h3>
        <!-- 定義一個(gè)插槽(挖個(gè)坑,等著組件的使用者進(jìn)行填充) -->
        <slot name="center">我是一些默認(rèn)值,當(dāng)使用者沒有傳遞具體結(jié)構(gòu)時(shí),我會(huì)出現(xiàn)1</slot>
        <slot name="footer">我是一些默認(rèn)值,當(dāng)使用者沒有傳遞具體結(jié)構(gòu)時(shí),我會(huì)出現(xiàn)2</slot>
    </div>
</template>
<script>
    export default {
        name: "Category",
        props:['title']
    }
</script>
<style scoped>
    .category {
        background-color: skyblue;
        width: 200px;
        height: 300px;
    }
    h3 {
        text-align: center;
        background-color: orange;
    }
    video {
        width: 100%;
    }
    img {
        width: 100%;
    }
</style>

4.4.3.作用域插槽

src/App.vue

<template>
    <div class="container">
        <Category title="游戲">
            <template scope="liqb">
                <ul>
                    <li v-for="(item, index) in liqb.games" :key="index">{{item}}</li>
                </ul>
            </template>
        </Category>
        <Category title="游戲">
            <template scope="{games}">
                <ol>
                    <li style="color:red" v-for="(item, index) in games" :key="index">{{item}}</li>
                </ol>
            </template>
        </Category>
        <Category title="游戲">
            <template slot-scope="{games}">
                <h4 v-for="(g,index) in games" :key="index">{{g}}</h4>
            </template>
        </Category>
    </div>
</template> 
<script> 
    // 引入組件
    import Category from './components/Category.vue';
    export default {
        name:'App',
        components:{
            Category
        }
    }
</script>
<style>
    .container,.foot {
        display: flex;justify-content: space-around;
    }
    h4{text-align: center;}
</style>

src/components/Category.vue

<template>
    <div class="category">
        <h3>{{title}}分類</h3>
        <slot :games="games" msg="hello">我是默認(rèn)的一些內(nèi)容</slot>
    </div>
</template>
<script>
    export default {
        name: "Category",
        props:['title'],
        data() {
            return {
                games: ['紅色警戒','穿越火線','勁舞團(tuán)','超級(jí)瑪麗']
            }
        }
    }
</script>
<style scoped>
    .category {
        background-color: skyblue;
        width: 200px;
        height: 300px;
    }
    h3 {
        text-align: center;
        background-color: orange;
    }
    video {
        width: 100%;
    }
    img {
        width: 100%;
    }
</style>

到此這篇關(guān)于Vue中的Ajax 配置代理 slot插槽的文章就介紹到這了,更多相關(guān)vue ajax配置slot插槽內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論