范围槽不是一个直观的概念。Vue文档使用描述性短语来解释作用域:
有时,您希望为组件提供一个可重用的插槽,可以从子组件获取数据.但是在应用程序的某些部分,我们希望每个独立的待办事项呈现与待办事项不同的内容。
但在我看来,至少在我第一次读的时候,这段话是相当难懂的。slot不是在向子组件分发内容吗,那么为什么要从子组件获取数据呢?难道没有办法通过emit事件将数据从子组件传递到父组件吗?你为什么需要它?范围槽是用来做什么的?……
在浏览了大量的博客,思考了“不这样会怎么样”之后,范围槽的含义逐渐清晰。事实上,范围槽提供了一种打包可重用组件的新思路。我将从最简单的例子开始。
简单演示列表
现在让我们制作一个用于纯显示的列表组件,如下图所示:
第一个示例使用slot首先分发内容
Template div class=' list ' div class=' list-title ' slot name=' title '/slot/div class=' list-content ' slot name=' content '/slot/div/div/Template脚本导出默认{ name : ' MyList ' }/脚本在父组件中使用my list
模板my list span slot=' title ' title/span ul slot=' content ' Li v-for='列表数据中的项目' { item } }/Li/ul/my list/template script import my list from '。/list . vue ';导出默认{name:' hello world ',components 3360 { ' my list ' : my list },data(){ return { listdata :[' list item 1 ',' listitem 2 ',' list item 3 ']}/脚本省略了样式代码,结果如图所示
基本要求都满足了,但是作为一个组件用户,这样的组件会让我觉得很麻烦,内容中的循环逻辑需要自己写,使用起来很不方便。下面是第二个版本
使用道具传输数据
因为考虑到列表的内容总是一个数组,所以我将循环结构写入组件
列表组件版本2:
template div class=' list ' div class=' list-title ' { title } }/div ul class=' list-content ' Li v-for='(item,index)in content ' : key=' index ' { item } }/Li/ul/div/template script export default { name : ' MyList ',prop s : { title : { type : string,必选3: true },content 3: { type 333: array,必选3:
模板div my list title=' title 1 ' : content='列表数据'/我的列表我的列表title=' title 2' :content='新列表数据'/我的列表/div/模板脚本导入我的列表来源'。/list . vue ';导出默认的{name:' hello world ',组件: {'mylist' : mylist},data(){ return { listdata :[' list item 1 ',' listitem 2 ',' listitem 3'],NewListData: ['新列表项1 ','新列表项2 ',} } }/脚本改进后,每次使用组件只需要一行代码,大大简化了工作量
易用性的需求也得到了满足,但是现在出现了新的问题,组件的扩展性不好!每次只能生成具有相同结构的列表。一旦业务需求改变,组件就不再适用。比如现在我有了新的需求,我在一个列表中的每个列表项前都加了一个小的logo,所以我不能写一个新的组件来适应需求的变化。如果需要更多定制场景怎么办?
范围槽
这是列表组件的第三个版本,它使用作用域槽传递子组件中的数据
template div class=' list ' div class=' list-title ' { title } }/div ul class=' list-content ' Li v-for='(item,index)in content ' : key=' index '!-这里,内容中的每一项数据都绑定到slot的item变量,可以从父组件-slot : item=' item ' { item } }/slot/Li/ul/div/template中获取item变量。使用组件时,业务所需的内容模板被传入。
模板div my list title=' title 1 ' : content=' listdata 1 '/my list my list title=' title 2 ' : content=' listdata 2 '模板槽-作用域=' scope ' img : src=' http : scope . item . img ' width=' 20 ' span { { scope . item . text } }/span/template/my list my list title=' title 3 ' : content=' listdata 3 '模板槽-作用域='作用域' { template前缀为“:”但没有前缀“}”span { { scope . item . text } }/span span { { scope . item . remote } }/span/template/my list/div/template script import my list from '。/list . vue ';导出默认{name:' hello world ',components : { ' my list ' : my list },data(){ return { listdata 1:[' list item 1 ',' listitem 2 ',' listitem 3'],listdata 2:[{ text : ' list item 1 ',img:' example.png'},{text:' list item 2 ',img3360' example.png'}
回到最初的问题,范围槽用于什么?很明显,它的功能就像官网说的:暴露组件的数据。通过这样做,组件的用户有机会根据数据定制模板,组件不再被写入特定的结构。
以上就是本文的全部内容。希望对大家的学习有帮助,支持我们。