vue组件化高级

tech2026-01-09  13

slot(插槽)

作用基本使用组件如何封装具名插槽编译作用域作用域插槽

作用

为了让封装的组件更加具有扩展性;让使用决定组件呢不展示的内容。

基本使用

使用标签栗子: 移动开发中,几乎每个页面都有导航栏;导航栏一般都会封装成一个插件,比如nav-bar组件;多个页面复用封装好的组件。 京东app中多个页面使用的导航栏

组件如何封装

提取共性,保留不同; 将共性抽取到组件中,将不同暴露给插槽;若预留插槽,让使用者根据自己需求,决定插槽中显示的内容;如搜索框、文字、菜单等,均由调用者决定。 项目中如何使用插槽 <slot>标签中的内容显示,若在该组件中未插内容,就默认显示该内容;可在父组件中使用 <div id = 'app'> <cpn><button>按钮</button></cpn> <cpn><span>内容</span></cpn> <cpn><i>样式</i></cpn> </div> <template id = 'cpn'> <div> <h2>我是组件中h2</h2> <p>我是组件内容</p> <!-- 使用slot标签插入插槽 --> <slot></slot> </div> </template> <div id = 'app'> <cpn></cpn> <cpn><span>哈哈哈</span></cpn> <cpn><i>呵呵呵</i></cpn> <cpn></cpn> </div> <template id = 'cpn'> <div> <h2>我是组件</h2> <p>我是组件,哈哈哈哈</p> <!-- slot插槽中设置默认值 --> <slot><button>按钮</button></slot> </div> </template>

具名插槽

使用插槽时,给插槽定义name属性;调用的时候要写slot="nameValue"。如下: <div id = 'app'> <cpn><span slot = 'center'>标题</span></cpn> <cpn><button slot = 'left'>返回</button></cpn> <cpn></cpn> </div> <template id = 'cpn'> <div> <!-- slot插槽中设置默认值 --> <slot><span name = 'left'>左边</span></slot> <slot><span name = 'center'>中间</span></slot> <slot><span name = 'right'>右边</span></slot> </div> </template>

编译作用域

什么是编辑作用域 类似Java方法中变量的作用域;官方准则:父组件模板的所有东西都会在父级作用域内编译;子组件模板的所有东西都会在自己作用域内编译。

作用域插槽

组件模板在使用变量的时候会从优先从当前模板拿数据;父组件模板的所有东西都会在父级作用域内编译;子组件模板的所有东西都会在子级作用域内编译。 栗子(父组件替换插槽标签,内容由子组件来提供): 需求: 子组件中包括一组数据,如: computer_language:['JavaScript', 'Phthon', 'Swift', 'Go', 'C++'];需要在多个界面以不同方式展示,如: 水平形式、列表形式、数组形式内容在子组件,父组件决定展示形式。 使用slot作用域插槽解决 通过<template slot-scope="slotProps">获取slotProps属性;再通过slotProps.data获取传入的data。 <div id="app"> <!-- 水平形式展示 中间用-分割 --> <cpn> <template slot-scope="slotProps"> //在父组件使用模板标签然后用slot-scope="slot"引入插槽元素 //调用模板数据的时候用join函数用于分割 <span v-for="item in slotProps.data.join('-')">{{item}}</span> </template> </cpn> <!-- 列表形式展示 --> <cpn> <template slot-scope="slotProps"> <ul> <li v-for="info in slotProps.data">{{info}}</li> </ul> </template> </cpn> </div> <template id="cpn"> <div> <slot :data="computer_language"> //在插槽标签中,绑定当前模板所在作用域的数据 <ul> <li v-for="item in computer_language">{{item}}</li> </ul> </slot> </div> </template> <script> const vm=new Vue({ el:'#app', data:{ message:'hello' }, components:{ cpn:{ template:'#cpn', data(){ return{ computer_language:['JavaScript', 'Phthon', 'Swift', 'Go', 'C++'] } } } } }) </script>
最新回复(0)