您的位置:首页技术文章
文章详情页

Vue作用域插槽实现方法及作用详解

【字号: 日期:2023-01-08 18:47:28浏览:2作者:猪猪

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

首先是有一个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='https://www.haobala.com/bcjs/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,出错的地方在这里:

Vue作用域插槽实现方法及作用详解

然后,引入一个插槽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
相关文章: