第四章 Vue 中的 ajax

第四章 Vue 中的 ajax

  • [4.1 解决开发环境 Ajax 跨域问题](#4.1 解决开发环境 Ajax 跨域问题)
  • [4.2 github案例](#4.2 github案例)
    • [4.2.1 静态组件](#4.2.1 静态组件)
      • [1 源代码](#1 源代码)
      • [2 细节问题](#2 细节问题)
    • [4.2.2 实现动态组件-列表展示](#4.2.2 实现动态组件-列表展示)
      • [1 源代码](#1 源代码)
      • [2 细节问题](#2 细节问题)
    • [4.2.3 完善案例](#4.2.3 完善案例)
      • [1 源代码](#1 源代码)
      • [2 细节问题](#2 细节问题)
  • [4.4 插槽](#4.4 插槽)

4.1 解决开发环境 Ajax 跨域问题

4.1.1 总结

Vue脚手架配置代理
方式一

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

javascript 复制代码
devServer:{
   proxy:"http://localhost:5000"
}

说明:

  • 优点:配置简单,请求资源时直接发给前端(8080)即可。
  • 缺点:不能配置多个代理,不能灵活的控制请求是否走代理。
  • 工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器(优先匹配前端资源)

方式二

编写vue.config.js配置具体代理规则:

javascript 复制代码
module.exports = {
	devServer: {
    proxy: {
      '/api1': { // 匹配所有以 '/api1' 开头的请求路径
        target: 'http://localhost:5000', // 代理目标的基础路径
				pathRewrite:{'^/api1':''},
        // ws: true, //用于支持websocket
        // changeOrigin: true //用于控制请求头中的host值
      },
      '/api2': { // 匹配所有以 '/api2' 开头的请求路径
        target: 'http://localhost:5001', // 代理目标的基础路径
				pathRewrite:{'^/demo':''},
        // ws: true, //用于支持websocket
        // changeOrigin: true //用于控制请求头中的host值
      }
    }
  }
}

/*
  changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
  changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080
  changeOrigin默认值为true
*/

说明:

  • 优点:可以配置多个代理,且可以灵活的控制请求是否走代理.
  • 缺点:配置略微繁琐,请求资源时必须加前缀。

4.1.2 源代码

服务器1代码

这是js文件

javascript 复制代码
const express = require('express')
const app = express()

app.use((request,response,next)=>{
	console.log('有人请求服务器1了');
	// console.log('请求来自于',request.get('Host'));
	// console.log('请求的地址',request.url);
	next()
})

app.get('/students',(request,response)=>{
	const students = [
		{id:'001',name:'tom',age:18},
		{id:'002',name:'jerry',age:19},
		{id:'003',name:'tony',age:120},
	]
	response.send(students)
})

app.listen(5000,(err)=>{
	if(!err) console.log('服务器1启动成功了,请求学生信息地址为:http://localhost:5000/students');
})

服务器2代码

这是js文件

javascript 复制代码
const express = require('express')
const app = express()

app.use((request,response,next)=>{
	console.log('有人请求服务器2了');
	next()
})

app.get('/cars',(request,response)=>{
	const cars = [
		{id:'001',name:'奔驰',price:199},
		{id:'002',name:'马自达',price:109},
		{id:'003',name:'捷达',price:120},
	]
	response.send(cars)
})

app.listen(5001,(err)=>{
	if(!err) console.log('服务器2启动成功了,请求汽车信息地址为:http://localhost:5001/cars');
})

浏览器端

vue.config.js

javascript 复制代码
module.exports = {
  pages: {
    index: {
      //入口
      entry: 'src/main.js',
    },
  },
	lintOnSave:false, //关闭语法检查
	//开启代理服务器(方式一)
	/* devServer: {
    proxy: 'http://localhost:5000'
  }, */
	//开启代理服务器(方式二)
	devServer: {
    proxy: {
      '/atguigu': {
        target: 'http://localhost:5000',
				pathRewrite:{'^/atguigu':''},
        // ws: true, //用于支持websocket
        // changeOrigin: true //用于控制请求头中的host值
      },
      '/demo': {
        target: 'http://localhost:5001',
				pathRewrite:{'^/demo':''},
        // ws: true, //用于支持websocket
        // changeOrigin: true //用于控制请求头中的host值
      }
    }
  }
}

App组件

javascript 复制代码
<template>
	<div>
		<button @click="getStudents">获取学生信息</button>
		<button @click="getCars">获取汽车信息</button>
	</div>
</template>

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

4.1.3 配置方式一(解决跨域)

开启服务器方式

首先在终端打开服务器所在目录,然后输入下述命令开启服务器,如下:

但这里推荐nodemon,Nodemon 是 Node.js 生态系统中一款非常实用的开发工具,用于监控文件的变化并自动重启服务器,从而提升开发效率。

  • 即只要你改了服务器代码,它就能自动监控到并自动重启,而使用node命令却不行

nodemon 全局安装命令:

javascript 复制代码
#全局安装
npm install -g nodemon

nodemon 局部安装命令:

javascript 复制代码
#项目局部安装
npm install --save-dev nodemon

在终端打开服务器所在目录,然后输入下述命令开启服务器,如下:

javascript 复制代码
nodemon server1.js

解决跨域

讨论一下ajax请求方式:

  • xhr,但真正开发中,很少用,因为太麻烦了。
  • JQuery,Vue项目很少使用,因为JQuery核心是封装DOM操作,而Vue核心是减少DOM操作,这不合适。
  • axios,它是promise风格,并且支持请求拦截器和响应拦截器,体积小,Vue推荐使用axios。
  • fetch,它不是基于xhr的封装,是JS内置的,与xhr平级,它是promise风格,但Vue尚未推荐,因为尚未成熟,fetch兼容性稍差。

axios下载命令如下:

javascript 复制代码
npm i axios

首先开启服务器,如下:

然后编写App组件如下:

但这样写会有问题,它会跨域。

  • 跨域(Cross-Origin)是指在网页中,浏览器的同源策略限制了不同源(域名、协议、端口)的网页之间的资源共享和交互。也就是说,一个网站的网页只能请求同一源(域名、协议、端口)下的资源,不能随意访问其他源的资源。

所谓同源策略是指:

接下来分析一下,我们用命令npm run serve启动一个Vue项目时,默认打开localhost:8080,浏览器使用8080端口发送请求,服务器收到了也返回了结果,浏览器也受到了,但由于跨域,所以浏览器并没有把结果显示出来。

要麻烦后端解决跨域的方式如下:

  • 解决跨域最标准的方式是cors ,它并不需要前端人员做任何事情,而是写服务器的人在服务器里面加多几个响应头,所以返回响应结果时,会携带几个特殊的响应头,浏览器就会认可。但真正开发时,响应头并不能随便配置,这样有可能任何人都能找你要数据。
  • jsonp,它利用srcipt标签src属性在引入外部资源不受同源策略影响,但开发几乎不用,它即麻烦前端,后端也得配合前端。(面试会问)

开发当中用的比较多的是:配置一个代理服务器 ,代理服务器所处端口号,跟目前浏览器所处端口号一致,如下:

它的步骤如下:

  • 浏览器发送请求给代理服务器
  • 代理服务器就把请求再转发给端口号为5000的服务器
  • 代理服务器接收响应并返回给浏览器

由于我们发请求时是发给代理服务器(端口为8080),所以就没有跨域问题了。

  • 服务器之间通常不会受到同源策略的限制 ,因为同源策略是由浏览器实现的,用来限制客户端(即用户的浏览器)之间的跨域访问。而服务器之间直接进行的通信不会受到这种限制。(代码上理解是服务器之间通信根本不用ajax,就只使用http请求)

开启代理服务器的方式有:

  • nginx,学习成本高,对后端技术要求高,不使用这个方式
  • 借助Vue-cli(我们使用的方式)

首先打开官方文档:https://v2.cn.vuejs.org/eol/,点击如下:

紧接着点击配置参考,ctrl+f搜索devServer,找到下图:

把里面的配置放到vue.config.js文件中,如下:

紧接着修改App组件代码如下:

这样获取学生信息就成了,如下:

但这种方式有一个缺点,当浏览器即开启的8080已经存在该资源,就不会将请求再发送给服务器了。(由于代理服务器端口相同,所以请求地址是"http://localhost:8080/students")

public文件夹就相当于8080服务器根路径,说明浏览器存在什么资源,如下:

那假设这个根路径有一个students文件,如下:

这样的话我们请求"http://localhost:8080/students"就没用了,它会去找这个根路径下的students,而不会发送请求给服务器了。

而且这种配置方式只能配置一个代理服务器。

4.1.3 配置方式二(解决跨域)

看官网,第二种配置方式如下:

首先配置代理服务器,如下:

然后配置App组件,如下:

这种方式有个问题,就是会带着一个不合理的路径发送给5000的服务器,这样就会发生错误,如下:

因此要使用重定位,将/atguigu给替换掉,如下:

  • 这是个正则表达式,^/atguigu意思是匹配所有以/atguigu开头的路径

该配置方式的ws属性解释起来很复杂,简单了解即可,主要再说说changeOrigin属性,如下:

  • changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
  • changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080
  • 它相当于伪造一个请求头,避免暴露真实的host,建议开启。

4.2 github案例

4.2.1 静态组件

1 源代码

src/components/Search.vue

javascript 复制代码
<template>
	<section class="jumbotron">
      <h3 class="jumbotron-heading">Search Github Users</h3>
      <div>
        <input type="text" placeholder="enter the name you search"/>&nbsp;<button>Search</button>
      </div>
    </section>
</template>

<script>

	export default {
		name:'Search',		
	}
</script>

src/components/List.vue

javascript 复制代码
<template>
	 <div class="row">
      <div class="card">
        <a href="https://github.com/xxxxxx" target="_blank">
          <img src="https://v2.cn.vuejs.org/images/logo.svg" style='width: 100px'/>
        </a>
        <p class="card-text">xxxxxx</p>
      </div>
      <div class="card">
        <a href="https://github.com/xxxxxx" target="_blank">
          <img src="https://v2.cn.vuejs.org/images/logo.svg" style='width: 100px'/>
        </a>
        <p class="card-text">xxxxxx</p>
      </div>
      <div class="card">
        <a href="https://github.com/xxxxxx" target="_blank">
          <img src="https://v2.cn.vuejs.org/images/logo.svg" style='width: 100px'/>
        </a>
        <p class="card-text">xxxxxx</p>
      </div>
      <div class="card">
        <a href="https://github.com/xxxxxx" target="_blank">
          <img src="https://v2.cn.vuejs.org/images/logo.svg" style='width: 100px'/>
        </a>
        <p class="card-text">xxxxxx</p>
      </div>
      <div class="card">
        <a href="https://github.com/xxxxxx" target="_blank">
          <img src="https://v2.cn.vuejs.org/images/logo.svg" style='width: 100px'/>
        </a>
        <p class="card-text">xxxxxx</p>
      </div>
    </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: .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>

src/App.vue

javascript 复制代码
<template>
	<div class="container">
		<Search/>
		<List/>
	</div>
</template>

<script>
	import Search from './components/Search'
	import List from './components/List'
	export default {
		name:'App',
		components:{Search,List}
	}
</script>

public/index.html

javascript 复制代码
<!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">
		<!-- 引入第三方样式 -->
		<link rel="stylesheet" href="<%= BASE_URL %>css/bootstrap.css">
		<!-- 配置网页标题 -->
    <title>硅谷系统</title>
  </head>
  <body>
		<!-- 当浏览器不支持js时noscript中的元素就会被渲染 -->
    <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>

public/css/bootstrap.css

去下载bootstrap.css的文件

2 细节问题

静态组件组成如下:里面的图片还可以单独拆成Item组件,但这里就不拆了。

这里主要讲一个细节问题:引入第三方样式的文件位置。

第一种方法

直接放到src文件夹下

之后一般是在App组件中引入:

但这种方式有一种问题,如果bootstrap.css第三方样式里面有一些我们未使用的文件夹,虽然未使用,但由于存在,但仍然报错,如下:

这是因为import'./assets/css/bootstrap.css'会进行非常严格的检查,只要第三方样式有不存在的资源,都一定会报错。

第二种方法

通过link方式引入,就不会有这种严格的检查。

首先在public文件夹引入bootstrap.css,如下:

然后在index.html文件使用link引入第三方样式,如下:

4.2.2 实现动态组件-列表展示

1 源代码

需要修改的代码有:

src/components/Search.vue

javascript 复制代码
<template>
	 <div class="row">
      <div class="card" v-for="user in users" :key="user.login">
        <a :href="user.html_url" target="_blank">
          <img :src="user.avatar_url" style='width: 100px'/>
        </a>
        <p class="card-text">{{user.login}}</p>
      </div>
    </div>
</template>

<script>
	export default {
		name:'List',
		data() {
			return {
				users:[]
			}
		},
		mounted() {
			this.$bus.$on('getUsers',(users)=>{
				this.users = users
			})
		},
	}
</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>

src/components/List.vue

javascript 复制代码
<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(){
				axios.get(`https://api.github.com/search/users?q=${this.keyWord}`).then(
					response => {
						console.log('请求成功了')
						this.$bus.$emit('getUsers',response.data.items)
						
					},
					error => {
						console.log('请求失败了',error.data)
					}
				)
			}
		},
	}
</script>

src/main.js

javascript 复制代码
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//关闭Vue的生产提示
Vue.config.productionTip = false

//创建vm
new Vue({
	el:'#app',
	render: h => h(App),
	beforeCreate(){
		Vue.prototype.$bus = this
	}
})

2 细节问题

Search组件使用"https://api.github.com/search/users?q=xxx"来发请求获得数据。

  • q=xxx中的xxx就是你Search的input框写入的内容

如下:

这里不需要考虑跨域问题,这个网站的后端程序员已经用cors解决了。

接下来加入搜索search,就会出现下述内容:

  • incomplete results:表示不完全的结果,即跟test相关的结果
  • items:根据算法选出来的30个
  • total count:表示总数

    紧接着就是把数据通过全局事件总线传到List组件的User里面,注意,当把信息存在data里,Vue会自动给它匹配get和set,这是基础内容。 我们需要数据items的三样东西,如下:
  • 第一个是用户头像地址
  • 第二个是可以跳转到用户主页
  • 第三个是用户名

全局事件总线代码并不难这些部分看源代码即可

4.2.3 完善案例

1 源代码

需要修改的组件有:

src/components/Search.vue

javascript 复制代码
<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(){
				//请求前更新List的数据
				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('请求成功了')
						//请求成功后更新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

javascript 复制代码
<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" 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>
		<!-- 展示错误信息 -->
		<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: .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>

2 细节问题

完善案例,List组件需要以下功能:

  • 初始时,需要显示欢迎词
  • 搜索时,网速慢时,需要显示搜索中
  • 发请求搜索成功时,显示结果
  • 发请求搜索失败时,显示错误

细节问题一

这里的isFirst只需要写一次即可,因为只有上来时要显示欢迎词,只要点了搜索,它永远消失;请求失败时,还要清空user

细节问题二

List组件拿数据时,不能用this.data(Vue规定),如下:

也不能像下图那样写,这样isFirst就消失了,在细节问题一中提到,isFirst只写一次。

所以要像下面这样写,它会把this.info和dataObj所有属性进行对比,重名属性以dataObj的值为主

javascript 复制代码
this.$bus.$on('updateListData',(dataObj)=>{
	this.info = {...this.info,...dataObj}
})

4.4 插槽

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

4.4.1 默认插槽

源代码

src/components/Category.vue

javascript 复制代码
<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%;
	}
</style>

src/App.vue

javascript 复制代码
<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 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 {
				foods:['火锅','烧烤','小龙虾','牛排'],
				games:['红色警戒','穿越火线','劲舞团','超级玛丽'],
				films:['《教父》','《拆弹专家》','《你好,李焕英》','《尚硅谷》']
			}
		},
	}
</script>

<style scoped>
	.container{
		display: flex;
		justify-content: space-around;
	}
</style>

细节

这里包一层,如下:

然后在App.vue组件传递具体结构,如下:

4.4.2 具名插槽

源代码

src/components/Category.vue

javascript 复制代码
<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>

src/App.vue

javascript 复制代码
<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>
			<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 {
				foods:['火锅','烧烤','小龙虾','牛排'],
				games:['红色警戒','穿越火线','劲舞团','超级玛丽'],
				films:['《教父》','《拆弹专家》','《你好,李焕英》','《尚硅谷》']
			}
		},
	}
</script>

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

细节问题

包裹一个div时,尽量不要再包裹div破坏结果

用template,如下:

4.4.2 作用域插槽

源代码

src/components/Category.vue

javascript 复制代码
<template>
	<div class="category">
		<h3>{{title}}分类</h3>
		<slot :games="games" msg="hello">我是默认的一些内容</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>

src/App.vue

javascript 复制代码
<template>
	<div class="container">

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

		<Category title="游戏">
			<template scope="{games}">
				<ol>
					<li style="color:red" v-for="(g,index) in games" :key="index">{{g}}</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'
	export default {
		name:'App',
		components:{Category},
	}
</script>

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

细节问题

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

首先App组件传数据,如下:

javascript 复制代码
<div class="category">
		<h3>{{title}}分类</h3>
		<slot :games="games" msg="hello">我是默认的一些内容</slot>
</div>

然后类似下图这样,用一个对象来接受,这个对象用于接收数据,假设你传了games1,games2,那么atguigu就有这两个属性(或者用{games1,games2}接收),也可以用slot-scope来接收,效果一样的。

相关推荐
醉城夜风~1 小时前
CSS元素显示模式(display)
前端·css
AI大模型-小华2 小时前
Codex 三方充值快速入门指南
java·前端·数据库·chatgpt·ai编程·codex·chatgpt pro
做前端的娜娜子4 小时前
同一链接实现 PC Web 与移动 H5 自适应
前端·掘金·金石计划
小帅不太帅4 小时前
架构没变、规模没变,DeepSeek V4 Flash 正式版凭什么暴涨 47 分?
前端·aigc·deepseek
jarvisuni4 小时前
DeepSeekFlash前端依旧拉垮,而且变慢了很多!
前端·javascript·算法
卷福同学6 小时前
AI编程出海第二步:验证关键词能否做站
前端·人工智能·后端
赵庆明老师6 小时前
Vben精讲:21-详解web-antd:tsconfig.json
前端·json·vim
wc886 小时前
微软EDGE浏览器功能学习
前端·学习·edge
Csvn7 小时前
🎯 原生 `<dialog>` 元素:终于可以扔掉一半的自定义弹窗组件了?
前端