不懂Vue作用域插槽的作用是什么?其实想解决这个问题也不难,下面让小编带着大家一起学习怎么去解决,希望大家阅读完这篇文章后大所收获。

默认插槽和具名插槽的概念比较好理解,这里主要以官方文档的案例来讲解一下作用域插槽。

首先是有一个currentUser的组件:

<!DOCTYPE html><html lang="zh-CN"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title></head><body> <div id="app"> <current-user> {{ user.firstName }} </current-user> </div> <script src="vue.min.js"></script> <script> Vue.component('currentUser', { template: ` <span> <slot>{{ user.lastName }}</slot> </span> `, data() { return { user: { firstName: 'w', lastName: 'ts' } } } }) new Vue({ el: '#app' }) </script></body></html>

然而该页面无法正常工作,因为只有currentUser可以访问到user,出错的地方在这里:

然后,引入一个插槽prop:

<span> <slot :user="user"> {{ user.lastName }} </slot></span>

接着,需要给v-slot带一个值来定义我们提供的插槽 prop 的名字:

<current-user> <template v-slot="wts"> {{ wts.user.firstName }} </template></current-user>

简单的讲作用域插槽就是让插槽内容能够访问子组件中才有的数据,修改后便可以正常工作了。

感谢你能够认真阅读完这篇文章,希望小编分享的Vue作用域插槽的作用是什么这篇文章内容对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,遇到问题就找亿速云,详细的解决方法等着你来学习!