Skip to content

4. Vue中的Ajax

4.1. Vue脚手架配置代理

配置代理可以用来解决跨域的问题

我们有两个nodejs写的服务器,运行:用 node 文件名 运行 ——> 用来模拟后端项目(后端服务器)

server1.js在电脑的5000端口

server2.js在电脑的5001端口

注:浏览器地址栏输入url,默认的就是get请求方式

ajax 是前端技术,你得有浏览器,才有window对象,才有xhr,才能发ajax请求,服务器之间通信就用传统的http请求就行了。

本案例需要下载axios库:npm install axios(默认就是--save的)

常用的发送Ajax请求的方式有哪些?

1.xhr

本质是new XMLHttpRequest()对象,xhr.open(),xhr.send()

2.jQuery

$.get $.post

本质是对xhr的封装

jQuery核心是dom操作,不符合vue的思想(尽量减少操作dom),所以我们ajax一般不用jQuery

3.axios(主流)

本质是对xhr的封装,Promise风格

4.fetch

与xhr是平级的,Promise风格

5.vue-sesource

vue的插件库,用的不太多了,vue1.0时候用的多

本质也是对xhr的封装,也是Promise风格

axios代码实现:

src/App.vue:

vue
<template>
    <div id="root">
        <button @click="getStudents">获取学生信息</button><br/>
        <button @click="getCars">获取汽车信息</button>
    </div>
</template>

<script>
    import axios from 'axios' //引入axios

    export default {
        name:'App',
        methods: {
			getStudents(){
				axios.get('localhost:5000/students').then(
					response => {
						console.log('请求成功了',response.data)
					},
					error => {
						console.log('请求失败了',error.message)
					}
				)
			},
            getCars(){
				axios.get('localhost:5000/cars').then(
					response => {
						console.log('请求成功了',response.data)
					},
					error => {
						console.log('请求失败了',error.message)
					}
				)
			}
        }
    }
</script>

跨域问题:CORS问题

跨域问题的原因就是违背了同源策略:协议名、主机名、端口号三者必须一致,否则就算跨域!

我们此次axios请求,就是违背了端口号一致的原则!

跨域是在浏览器形成拦截的,其实我们的请求发到了服务器,服务器也返回了数据,只是浏览器发现了我们跨域了,不把数据给我们!

所以说,服务器和服务器之间不存在跨域,而浏览器和服务器之间是存在跨域的,而ajax请求恰好就必须要借助浏览器来发送!

解决跨域问题的方法:

1.cors

服务器在响应时携带一些特殊的响应头,这样浏览器就不会拦截跨域了

不需要前端人员的任何操作

但是这种方式不好,因为这样就所有人都可以管我们的服务器要数据了

2.jsonp

借助script标签的src属性在引入外部资源不受同源策略限制的特点

并且只能解决get请求的跨域问题

并且需要前端和后端一起操作

所以实际开发中几乎没有用的(但是面试喜欢问)

3.配置代理服务器

代理服务器和前端项目的端口号等都一样(不存在跨域),浏览器发请求先发给代理服务器,然后让代理服务器发请求到真正的服务器,然后我们的项目就一定可以收到数据了!

服务器和服务器之间不存在跨域(这里不存在ajax,只有浏览器才有ajax,ajax是前端技术)

那么怎么开启这个代理服务器呢?

(1)Nginx

(2)vue-cli(简单)

在这里插入图片描述

开发中最常使用的方式!

解决跨域的代码实现:

利用vue-cli自带的代理服务器(与脚手架项目开在同一个端口号)

vue.config.js:

js
module.exports = {

    pages: {

        index: {

            entry: 'src/main.js',
        },
    },
    lintOnSave:false,  //关闭语法检查
    // 开启代理服务器(方式一):代理服务器会自动开在8080,我们只需要告诉代理服务器需要把请求转发到哪里,所以这个proxy写后端项目的端口号
    // devServer: {

    //     proxy:'localhost:5000'
    // }

    //开启代理服务器(方式二):可以配置多个代理
	devServer: {

        proxy: {

            '/jojo': { //意思是如果请求路径的最前面加了/jojo,那么就走代理服务器,如果没加的话,那么就不走代理服务器

                target: 'localhost:5000',
                pathRewrite:{'^/jojo':''}, //把请求的url的前面的/jojo前缀去掉,再把请求发送给5000端口
                // ws: true, //用于支持websocket(后端的技术),默认值为true
                // changeOrigin: true //用于控制请求头中的host值,默认值为true,true的话就会将请求头端口号模拟成和后端服务器一样的端口,如果为false就会实话实说
            },
            '/atguigu': {

                target: 'localhost:5001',
                pathRewrite:{'^/atguigu':''},
                // ws: true, //用于支持websocket(后端的技术),默认值为true
                // changeOrigin: true //用于控制请求头中的host值,默认值为true,true的话就会将请求头端口号模拟成和后端服务器一样的端口,如果为false就会实话实说
            }
        }
    }
}

src/App.vue:需要改一下请求的端口号,请求代理服务器的8080端口,还有请求的前缀也要改!

vue
<template>
    <div id="root">
        <button @click="getStudents">获取学生信息</button><br/>
        <button @click="getCars">获取汽车信息</button>
    </div>
</template>

<script>
    import axios from 'axios' //引入axios

    export default {
        name:'App',
        methods: {
			getStudents(){
				axios.get('localhost:5000/jojo/students').then(
					response => {
						console.log('请求成功了',response.data)
					},
					error => {
						console.log('请求失败了',error.message)
					}
				)
			},
            getCars(){
				axios.get('localhost:5000/atguigu/cars').then(
					response => {
						console.log('请求成功了',response.data)
					},
					error => {
						console.log('请求失败了',error.message)
					}
				)
			}
        }
    }
</script>

效果:

img

注:不是所有的请求代理服务器都会转发给后端项目,当请求的内容代理服务器本来就有,那么直接认为请求到了,把这个文件就返回给前端,就不会把请求发给后端

什么意思?

项目的public目录就是8080代理服务器的根目录,我们在public下面创建一个test.txt,然后我们浏览器去请求localhost:8080/test.txt,就可以直接拿到文件内容,所以说我们在写请求时注意路径内容不要和public目录下的内容重名!

总结:

vue脚手架配置代理服务器:

  • 方法一:在vue.config.js中添加如下配置:

    js
    devServer:{
        proxy:"localhost:5000"
    }

    说明:

    • 优点:配置简单,请求资源时直接发给前端即可

    • 缺点:不能配置多个代理,不能灵活的控制请求是否走代理

    • 工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器 (优先匹配前端资源)

  • 方法二:在vue.config.js中添加如下配置:

    js
    devServer: {
        proxy: {
          	'/api1': { // 匹配所有以 '/api1'开头的请求路径
            	target: 'localhost:5000',// 代理目标的基础路径
            	changeOrigin: true,
            	pathRewrite: {'^/api1': ''}
          	},
          	'/api2': { // 匹配所有以 '/api2'开头的请求路径
            	target: 'localhost:5001',// 代理目标的基础路径
            	changeOrigin: true,
            	pathRewrite: {'^/api2': ''}
          	}
        }
    }
    
    // changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
    // changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080

    说明:

  • 优点:可以配置多个代理,且可以灵活的控制请求是否走代理

  • 缺点:配置略微繁琐,请求资源时必须加前缀

4.2. GitHub用户搜索案例

组件的拆分:Search和List

注意:引入第三方样式库时候,有两个方案

1.在src的assets文件夹下面创建css文件夹,放入bootstrap.css文件

在App.vue中写:import './assets/css/bootstrap.css'

缺点:会有严格的检查,比如bootstrap中用到的字体,如果我们没有,那么就会报错,需要全部下载配置好才可以

2.在public文件夹下面创建css文件夹,放入bootstrap.css文件

在index.html中写:<link rel="stylesheet" href="<%= BASE_URL %>css/bootstrap.css">

优点:不会有严格的检查,当我们在用不到第三方库的全部样式时,可以使用这种方法引入

public/index.html:

html
<!DOCTYPE html>
<html lang="">
    <head>
        <meta charset="UTF-8">
        <!-- 针对IE浏览器的特殊配置,含义是让IE浏览器以最高渲染级别渲染页面 -->
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <!-- 开启移动端的理想端口 -->
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <!-- 配置页签图标 -->
        <link rel="icon" href="<%= BASE_URL %>favicon.ico">
        <!-- 引入bootstrap样式 -->
        <link rel="stylesheet" href="<%= BASE_URL %>css/bootstrap.css">
        <!-- 配置网页标题 -->
        <title><%= htmlWebpackPlugin.options.title %></title>
    </head>
    <body>
        <!-- 容器 -->
        <div id="app"></div>
    </body>
</html>

src/main.js:

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:

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:

github提供的一个免费的接口:https://api.github.com/search/users?q=xxx,用于搜索用户,一个很普通的get请求,这个接口不涉及跨域,已经在后台解决了!

我们在search组件中搜索到的数据,要用$bus传给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="getUsers">Search</button>
		</div>
    </section>
</template>

<script>
    import axios from 'axios'
    export default {
        name:'Search',
        data() {
            return {
                keyWord:''
            }
        },
        methods: {
            getUsers(){
                //1.点击搜索后 清空数组,更新状态标志变量
                //传入的参数为一个对象,包括需要的标志变量(这样就不需要写多个函数了),这里之所以要写完整的对象,是因为这样更加语义化,并且另一边用到了动态合并
                //只有这里需要将isFirst:false,后面就不用管了
                //注:这里参数的位置是无所谓的,因为另一边是动态合并的
				this.$bus.$emit('searchListData',{isLoading:true,errMsg:'',users:[],isFirst:false});
                //2.正式发送ajax请求,得到返回的数据,更新状态标志变量
                //使用ES6的模板字符串,用``包裹,然后${}里面可以写js表达式,可以取变量
				axios.get(`https://api.github.com/search/users?q=${this.keyWord}`).then(
					response => {
						console.log('请求成功了')
						//请求成功后更新List的数据
						this.$bus.$emit('searchListData',{isLoading:false,errMsg:'',users:response.data.items})
					},
					error => {
						//请求失败后返回错误信息,清空数组
						this.$bus.$emit('searchListData',{isLoading:false,errMsg:error.message,users:[]})
					}
				);
            }
        }
    }
</script>

src/components/List.vue:

应当呈现四个效果:1.welcome欢迎语 2.loading加载显示信息 3.users用户信息列表 4.error错误信息

根据users数组长度,并不能判断处于哪个状态,所以要单独设置标志变量: isFirst, isLoading, errMsg:''等

标志变量要随着请求的结果动态地发生变化!

vue
<template>
    <div class="row">
        <!-- 展示用户列表,用户数组长度不为0时 -->
        <div class="card" v-show="info.users.length" v-for="user in info.users" :key="user.id">
            <!--主页的链接地址-->
            <a :href="user.html_url" target="_blank">
                <!--属性值v-bind动态绑定,头像-->
                <img :src="user.avatar_url" style='width: 100px'/>
            </a>
            <!--标签里面的标签体用插值语法,用户名-->
            <h4 class="card-title">{{user.login}}</h4>
        </div>
        <!-- 展示欢迎词,第一次使用的时候 -->
        <h1 v-show="info.isFirst">欢迎使用!</h1>
        <!-- 展示加载中,正在搜索的时候 -->
        <h1 v-show="info.isLoading">加载中...</h1>
        <!-- 展示错误信息,请求出错时 -->
        <h1 v-show="info.errMsg">{{errMsg}}</h1>
    </div>
</template>

<script>
    export default {
        name:'List',
        data() {
            return {
                info:{ //全部信息
                    isFirst:true, //是否为初次展示(一上来的样子,只有这一个时间点为true)
                    isLoading:false, //是否处于加载中(点了search按钮之后)
                    errMsg:'', //错误信息
                    users:[] //用户信息数据
                }
            }
        },
        mounted(){
            this.$bus.$on('searchListData',(dataObj)=>{
                //注意:不能用this._data = dataObj,因为这样会把响应式的get和set弄没,我们在使用vue时候一定不能直接操作_data,不可能出现这样的操作!
                //这样的话,后面会失去isFirst这个属性字段,不太好
                //this.info = dataObj
                //ES6的扩展运算符方法:动态合并两个对象的属性(取并集,相同的属性名以后面的属性值为准,并且不在乎属性的位置顺序,只要有即可),dataObj为传入的info信息,info为自己本来的信息
                this.info = {...this.info,...dataObj}
            })
        },
        beforeDestroy(){
            this.$bus.$off('updateListData')
        }
    }
</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: .75rem;
		margin-bottom: 2rem;
		border: 1px solid #efefef;
		text-align: center;
	}

	.card > img {
		margin-bottom: .75rem;
		border-radius: 100px;
	}

	.card-text {
		font-size: 85%;
	}
</style>

效果:

img

4.3. vue-resource

下载 vue-resource库:npm i vue-resource

src/main.js:

js
import Vue from 'vue'
import App from './App.vue'
import vueResource from 'vue-resource'

Vue.config.productionTip = false
Vue.use(vueResource) //使用插件,这样vm和vc都多了$http等4个属性

new Vue({

    el:"#app",
    render: h => h(App),
    beforeCreate(){

        Vue.prototype.$bus = this
    }
})

src/App.vue:

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:

改动就是由axios.get变成了this.$http.get,其他没有任何区别!!!

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="getUsers">Search</button>
		</div>
    </section>
</template>

<script>
    export default {
        name:'Search',
        data() {
            return {
                keyWord:''
            }
        },
        methods: {
            getUsers(){
                //请求前更新List的数据
				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('请求成功了')
						//请求成功后更新List的数据
						this.$bus.$emit('updateListData',{isLoading:false,errMsg:'',users:response.data.items})
					},
					error => {
						//请求后更新List的数据
						this.$bus.$emit('updateListData',{isLoading:false,errMsg:error.message,users:[]})
					}
				)
            }
        }
    }
</script>

src/components/List.vue:

vue
<template>
    <div class="row">
        <!-- 展示用户列表 -->
        <div class="card" v-show="info.users.length" v-for="user in info.users" :key="user.id">
            <a :href="user.html_url" target="_blank">
                <img :src="user.avatar_url" style='width: 100px'/>
            </a>
            <h4 class="card-title">{{user.login}}</h4>
        </div>
        <!-- 展示欢迎词 -->
        <h1 v-show="info.isFirst">欢迎使用!</h1>
        <!-- 展示加载中 -->
        <h1 v-show="info.isLoading">加载中...</h1>
        <!-- 展示错误信息 -->
        <h1 v-show="info.errMsg">{{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}
            })
        },
        beforeDestroy(){
            this.$bus.$off('updateListData')
        }
    }
</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: .75rem;
		margin-bottom: 2rem;
		border: 1px solid #efefef;
		text-align: center;
	}

	.card > img {
		margin-bottom: .75rem;
		border-radius: 100px;
	}

	.card-text {
		font-size: 85%;
	}
</style>

总结:

vue项目常用的两个Ajax库:

  1. axios:通用的Ajax请求库,官方推荐,效率高
  2. vue-resource:vue插件库,vue 1.x使用广泛,官方已不维护

4.4. slot插槽

4.4.1. 默认插槽

需求:美食模块展示图片,电影模块展示视频,而游戏模板展示列表,但是三个模块的模板都是一样的,怎么实现?

使用slot插槽:挖个坑,想展示什么就填什么!——>本质就是降低耦合性

src/App.vue:

注:由于填充的内容都是在App组件里面完成解析之后,才传入Category的插槽中的,所以css样式写在App组件里面也可以,写在Category里面也可以!

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="(g,index) in games" :key="index">{{g}}</li>
			</ul>
		</Category>

		<Category title="电影">
             <!--必须给video标签加上controls属性,才能控制视频的播放-->
			<video controls src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"></video>
		</Category>
	</div>
</template>

<script>
	import Category from './components/Category'
	export default {
		name:'App',
		components:{Category},
		data() {
			return {
				games:['植物大战僵尸','红色警戒','空洞骑士','王国']
			}
		},
	}
</script>

<style scoped>
	.container{
		display: flex;
		justify-content: space-around; /*中心轴水平排开*/
	}
</style>

src/components/Category.vue:

vue
<template>
	<div class="category">
		<h3>{{title}}分类</h3>
		<!-- 定义一个插槽(挖个坑,等着组件的使用者进行填充),前面的组件标签体里面的内容会填充到这个里面 -->
		<slot>我是一些默认值,当使用者没有传递具体结构时,我会出现</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%; /*撑开,就是只占父组件的100%,所以这样就不会溢出了*/
	}
</style>

效果:

img

4.4.2. 具名插槽

要指定slot="",而solt那边要指定name="",这样就会将对应的内容填到对应的坑里面!

src/App.vue:

vue
<template>
	<div class="container">
		<Category title="美食" >
			<img slot="center" src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg" alt="">
			<a slot="footer" href="http://www.atguigu.com">更多美食</a>
		</Category>

		<Category title="游戏" >
			<ul slot="center">
				<li v-for="(g,index) in games" :key="index">{{g}}</li>
			</ul>
			<div class="foot" slot="footer">
				<a href="http://www.atguigu.com">单机游戏</a>
				<a href="http://www.atguigu.com">网络游戏</a>
			</div>
		</Category>

		<Category title="电影">
			<video slot="center" controls src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"></video>
            <!--有很多元素想要放在footer中,可以这样写,外面包个会消失的template,一旦用了template,就可以使用v-slot: 了(但是仅能用在template上面)-->
			<template v-slot:footer>
				<div class="foot">
					<a href="http://www.atguigu.com">经典</a>
					<a href="http://www.atguigu.com">热门</a>
					<a href="http://www.atguigu.com">推荐</a>
				</div>
				<h4>欢迎前来观影</h4>
			</template>
		</Category>
	</div>
</template>

<script>
	import Category from './components/Category'
	export default {
		name:'App',
		components:{Category},
		data() {
			return {
				games:['植物大战僵尸','红色警戒','空洞骑士','王国']
			}
		},
	}
</script>

<style>
	.container,.foot{
		display: flex;
		justify-content: space-around;
	}
	h4{
		text-align: center;
	}
</style>

src/components/Category.vue:

vue
<template>
	<div class="category">
		<h3>{{title}}分类</h3>
		<!-- 定义一个插槽(挖个坑,等着组件的使用者进行填充) -->
		<slot name="center">我是一些默认值,当使用者没有传递具体结构时,我会出现1</slot>
        <slot name="footer">我是一些默认值,当使用者没有传递具体结构时,我会出现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>

效果:

img

4.4.3. 作用域插槽

需求:三者的标号类型不一样,但是展示的都是数据

src/App.vue:

这里必须都用标签包裹要传入的代码,并且指定scope

scope任意,但是这个scope会收到插槽上面绑定的数据(有可能是多个绑定的数据)

比如下面的jojo里面有games的全部数据,需要用jojo.games获取到数据!

vue
<template>
	<div class="container">
		<Category title="游戏" >
			<template scope="jojo">
				<ul>
					<li v-for="(g,index) in jojo.games" :key="index">{{g}}						</li>
				</ul>
			</template>
		</Category>

		<Category title="游戏" >
			<template scope="jojo">
				<ol>
					<li v-for="(g,index) in jojo.games" :key="index">{{g}}						</li>
				</ol>
			</template>
		</Category>

		<Category title="游戏" >
			<template scope="jojo">
				<h4 v-for="(g,index) in jojo.games" :key="index">{{g}}</h4>
			</template>
		</Category>
	</div>
</template>

<script>
	import Category from './components/Category'
	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:

作用域插槽理解:结构是正着传过来的,数据是逆着传回去的(传给插槽的使用者)

vue
<template>
	<div class="category">
		<h3>{{title}}分类</h3>
		<!-- 把games数据绑定给插槽的填充者:也相当于是子组件给父组件传值 -->
		<slot :games="games">我是一些默认值,当使用者没有传递具体结构时,我会出现			1</slot>
	</div>
</template>

<script>
	export default {
		name:'Category',
		props:['title'],
         data() {
			return {
				games:['植物大战僵尸','红色警戒','空洞骑士','王国']
			}
		},
	}
</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>

注:版本更新后,出现了新的api,还有使用 slot-scope 及 ES6中的解构赋值 的方式来指定作用域对象

slot-scope="{}"

vue
<Category title="游戏" >
    <!--这里相当于指定地接收对象的哪个属性,其实这个对象本质还是jojo,但是我们只接受它的games这一个属性,叫做解构赋值!-->
    <template slot-scope="{games}">
		<ul>
        	<li v-for="(g,index) in games" :key="index">{{g}}							</li>
        </ul>
    </template>
</Category>

或者:scope="{}"

vue
<Category title="游戏" >
    <template scope="{games}">
		<ul>
        	<li v-for="(g,index) in games" :key="index">{{g}}							</li>
        </ul>
    </template>
</Category>

注:据说现在的写法是v-solt="{}",之前的写法已经废弃了!

vue
<Category title="游戏" >
    <template v-solt="{games}">
		<ul>
        	<li v-for="(g,index) in games" :key="index">{{g}}							</li>
        </ul>
    </template>
</Category>

效果:

img

4.4.4. 总结

插槽:

  1. 作用:让父组件可以向子组件指定位置插入html结构,也是一种组件间通信的方式,适用于父组件 ==> 子组件(之前是子到父)

    注1:和props的区别:props是父到子传递data数据,solt是父到子传递html结构!

    注2:作用域插槽还有一点 子组件==>父组件 传递数据的意味,类似于之前的props传递函数,但是也有不同,因为这个作用域插槽的数据是在结构中直接用的,而之前的props传递函数的数据是在函数中用的(并且作用域插槽要求子组件必须使用插槽才可以传递数据)

  2. 分类:默认插槽、具名插槽、作用域插槽

  3. 使用方式:

    category是类别的意思

  • 默认插槽:

    vue
    父组件中:
            <Category>
               	<div>html结构1</div>
            </Category>
    子组件中:
            <template>
                <div>
                   	<slot>插槽默认内容...</slot>
                </div>
            </template>
  • 具名插槽

    vue
    父组件中:
    <Category>
        <template slot="center">
    		<div>html结构1</div>
        </template>
    
        <template v-slot:footer>
    		<div>html结构2</div>
        </template>
    </Category>
    子组件中:
    <template>
        <div>
        	<slot name="center">插槽默认内容...</slot>
    		<slot name="footer">插槽默认内容...</slot>
    	</div>
    </template>
  • 作用域插槽:

    1. 理解:数据在组件的自身(Category组件中),但根据数据生成的结构需要组件的使用者(传入插槽的内容)来决定。(games数据在Category组件中,但使用数据所遍历出来的结构由App组件决定)

      也就是说结构和数据是分离的,彼此谁都不能移动位置(实际工作场景可能遇到),只能进行通讯!

      比如在用第三方组件时,组件内部没有数据只有结构,需要我们自己定义插槽来接收

    2. 具体编码:

      vue
      父组件中:
      <Category>
          <template scope="scopeData">
      <!-- 生成的是ul列表 -->
      		<ul>
          		<li v-for="g in scopeData.games" :key="g">{{g}}</li>
              </ul>
          </template>
      </Category>
      
      <Category>
          <template slot-scope="scopeData">
      <!-- 生成的是h4标题 -->
      		<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'],
              //数据在子组件自身
              data() {
                  return {
                      games:['红色警戒','穿越火线','劲舞团','超级玛丽']
                  }
              },
          }
      </script>