vue slot的使用
一、自定義組件中多個(gè) slot
? ? 很久之前就想把表格封裝了,奈何那時(shí)太過(guò)擔(dān)心自己的技術(shù)。今天趁著勁頭大致看了一下,把表格封裝了,倒是比想象中的要簡(jiǎn)單很多 O(∩_∩)O 哈哈~?
? ? 暫且不考慮細(xì)節(jié),大致封裝表格要考慮的有:是否需要操作按鈕、是否要對(duì)表格中的某些字段值進(jìn)行修改或操作。這些就要用到多個(gè) slot,我們要做的就是區(qū)分這些 slot,在對(duì)應(yīng)的 slot 下寫(xiě)邏輯。
只有一個(gè) slot 時(shí),我們只需要在組件中想要改寫(xiě)的位置插入?<slot></slot> 標(biāo)簽就可以了。當(dāng)有多個(gè)時(shí),我們要在 slot 標(biāo)簽中寫(xiě)入?name 屬性對(duì) slot 進(jìn)行區(qū)分。例如:
子組件:
<div><slot name="a"><slot><h2>標(biāo)題</h2><p>段落文字文字文字文字</p><slot name="b"><slot> </div>父組件使用:
<my-text><h1 slot="a">我是大標(biāo)題</h1> <!-- 父組件中的slot值對(duì)應(yīng)子組件中name的值 --><span slot="b">20121-7-16</span> </my-text><script>import myText from "組件所在路徑";export default {components: { myText }} </script>?二、slot 傳參(利用 slot 子組件給父組件傳參)
? ?1. 插槽傳值::自定義屬性=值
? ? 如果要封裝表格,有很多表格中都是會(huì)有一些操作,例如刪除某一條數(shù)據(jù)、修改某條數(shù)據(jù),父組件都要從子組件中拿到對(duì)應(yīng)的 id 或者那一列的數(shù)據(jù)。這里我們只要在子組件的 slot 插槽中綁定一個(gè)自定義屬性,再把值傳給這個(gè)屬性就好了,例如:
模板中使用:???????
子組件:?
<el-table-column v-if="operateShow" label="操作" align="center" :min-width="operateWidth" fixed="right"><template slot-scope="scope"><!-- 自定義data屬性,把值傳給data屬性。這個(gè)data是自己隨便定義的一個(gè)名稱(chēng) --><slot name="operate" :data="scope.row"></slot></template> </el-table-column>父組件:
<!-- 父組件接收參數(shù)時(shí):slot-scope="自定義名稱(chēng)" --> <template slot="operate" slot-scope="myProps"><!-- 調(diào)用數(shù)據(jù):父組件slot-scope的自定義名稱(chēng).子組件slot標(biāo)簽中自定義數(shù)據(jù)名稱(chēng).需要且有效的字段名 --><el-button type="warning" size="mini" icon="el-icon-edit-outline" @click="update(myProps.data.url)">下載</el-button> </template>?循環(huán)中使用:
子組件:
<!-- 與在模板中直接使用的方法相同,:data傳的是表格中每一行的所有數(shù)據(jù),:index傳的是所在行的索引 --> <template v-for="(info, infoIndex) in tableInfo"><el-table-column :key="infoIndex" :prop="info.key" :label="info.value" align="center" :min-width="info.minWidth" show-overflow-tooltip ><!-- 給插槽命名、傳值、序列號(hào) --><slot :name="info.key" :data="info" :index="infoIndex"></slot></el-table-column> </template>父組件:
<!-- slot="所在列的某一個(gè)字段",并將這一列的字段值做處理 --> <template slot="downloadDate" ><span>112</span> </template>2. 通過(guò)事件給父組件傳值
? 這是自定義組件中最常用的一直方法。
子組件:通過(guò)?this.$emit()?的方式將值傳遞給父組件。
<template><div class="app"><input @click="sendMsg" type="button" value="給父組件傳遞值"></div> </template> <script> export default {data () {return {//將msg傳遞給父組件msg: "我是子組件的msg",}},methods:{sendMsg(){//func: 是父組件指定的傳數(shù)據(jù)綁定的函數(shù),this.msg:子組件給父組件傳遞的數(shù)據(jù)this.$emit('func',this.msg)}} } </script>?父組件:
<template><div class="app"><child @func="getMsgFormSon"></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)}} }總結(jié)
以上是生活随笔為你收集整理的vue slot的使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: canvas1:简单介绍、开始使用、画直
- 下一篇: vue 简单实用的elementUI表格