阿里云主机建网站,可以做微课PPT模板 网站,从0到建网站,四川建筑人员信息查询一、自定义组件中多个 slot 很久之前就想把表格封装了#xff0c;奈何那时太过担心自己的技术。今天趁着劲头大致看了一下#xff0c;把表格封装了#xff0c;倒是比想象中的要简单很多 O(∩_∩)O 哈哈~ 暂且不考虑细节#xff0c;大致封装表格要考虑的有#xff1a;是否…一、自定义组件中多个 slot 很久之前就想把表格封装了奈何那时太过担心自己的技术。今天趁着劲头大致看了一下把表格封装了倒是比想象中的要简单很多 O(∩_∩)O 哈哈~ 暂且不考虑细节大致封装表格要考虑的有是否需要操作按钮、是否要对表格中的某些字段值进行修改或操作。这些就要用到多个 slot我们要做的就是区分这些 slot在对应的 slot 下写逻辑。
只有一个 slot 时我们只需要在组件中想要改写的位置插入 slot/slot 标签就可以了。当有多个时我们要在 slot 标签中写入 name 属性对 slot 进行区分。例如
子组件
divslot nameasloth2标题/h2p段落文字文字文字文字/pslot namebslot
/div
父组件使用
my-texth1 slota我是大标题/h1 !-- 父组件中的slot值对应子组件中name的值 --span slotb20121-7-16/span
/my-textscriptimport myText from 组件所在路径;export default {components: { myText }}
/script 二、slot 传参利用 slot 子组件给父组件传参 1. 插槽传值:自定义属性值 如果要封装表格有很多表格中都是会有一些操作例如删除某一条数据、修改某条数据父组件都要从子组件中拿到对应的 id 或者那一列的数据。这里我们只要在子组件的 slot 插槽中绑定一个自定义属性再把值传给这个属性就好了例如
模板中使用
子组件
el-table-column v-ifoperateShow label操作 aligncenter :min-widthoperateWidth fixedrighttemplate slot-scopescope!-- 自定义data属性把值传给data属性。这个data是自己随便定义的一个名称 --slot nameoperate :datascope.row/slot/template
/el-table-column
父组件
!-- 父组件接收参数时slot-scope自定义名称 --
template slotoperate slot-scopemyProps!-- 调用数据父组件slot-scope的自定义名称.子组件slot标签中自定义数据名称.需要且有效的字段名 --el-button typewarning sizemini iconel-icon-edit-outline clickupdate(myProps.data.url)下载/el-button
/template 循环中使用
子组件
!-- 与在模板中直接使用的方法相同:data传的是表格中每一行的所有数据:index传的是所在行的索引 --
template v-for(info, infoIndex) in tableInfoel-table-column :keyinfoIndex :propinfo.key :labelinfo.value aligncenter :min-widthinfo.minWidth show-overflow-tooltip !-- 给插槽命名、传值、序列号 --slot :nameinfo.key :datainfo :indexinfoIndex/slot/el-table-column
/template 父组件
!-- slot所在列的某一个字段并将这一列的字段值做处理 --
template slotdownloadDate span112/span
/template 2. 通过事件给父组件传值 这是自定义组件中最常用的一种方法。
子组件通过 this.$emit() 的方式将值传递给父组件。
templatediv classappinput clicksendMsg typebutton value给父组件传递值/div
/template
script
export default {data () {return {//将msg传递给父组件msg: 我是子组件的msg,}},methods:{sendMsg(){//func: 是父组件指定的传数据绑定的函数this.msg:子组件给父组件传递的数据this.$emit(func,this.msg)}}
}
/script 父组件 templatediv classappchild funcgetMsgFormSon/child/div
/template
script
import child from ./child.vue
export default {data () {return {msgFormSon: this is msg}},components:{child,},methods:{getMsgFormSon(data){this.msgFormSon dataconsole.log(this.msgFormSon)}}
} 三、v2.6.0关于slot的新写法
插槽 — Vue.js 在 2.6.0 中我们为具名插槽和作用域插槽引入了一个新的统一的语法 (即 v-slot 指令)。它取代了 slot 和 slot-scope 这两个目前已被废弃但未被移除且仍在文档中的 attribute。