最終實現方式在最后面
博客園你啊347
在開發的時候有一個小需求
在一個步驟列表中, 每個步驟有步驟id,步驟描述, 步驟圖片, 步驟視頻這幾個基本元素
其中, 步驟視頻是非必要的, 可以為空(null 或 empty, 這個有點扯, 居然沒有統一)
然后具體需求是: 當鼠標懸浮在圖片上時, 利用popover, 在圖片的右側(placement="right") 顯示視頻
(視頻組件直接用的video標簽實現的) 博客園你啊347
那么查看elementUI的組件文檔可以知道, 觸發Popover的元素有兩種寫法
1. 使用slot="reference"博客園你啊347
2. 使用自定義指令v-popover指向Popover的索引ref博客園你啊347
(參考elementUI文檔https://element.eleme.cn/2.13/#/zh-CN/component/popover)
一開始用的是第一種, 但是后面發現在這個需求里面會有點問題博客園你啊347
點擊查看代碼
<div
class="item"
v-for="(item, index) in array.steps"
:key="index"
>
<el-popover
v-if="item.video && item.video !== ''"
placement="right"
title="步驟視頻"
trigger="hover"
>
<video
:src="item.video"
controls="controls"
style="width: 400px; height: 300"
></video>
<!--這里是做popover的slot-->
<div class="image" slot="reference">
<el-image
:src="item.photo"
style="width: 100%; height: 100%"
fit="cover"
:z-index="2030"
>
</el-image>
</div>
</el-popover>
</div>
可以看到, 整個步驟列表循環是通過 v-for="(item, index) in array.steps" 進行控制的
然后把el-popover放在里面就可以實現 每個步驟一個popover,
再把slot指定為el-image外面那個盒子, 以此實現懸浮顯示對應步驟視頻的需求
但是, 這里有個問題, 就是 v-if="item.video && item.video !== ''" 這段代碼如果不成立的話, 那么圖片也會跟着不顯示博客園你啊347
所以這個需求用slot這個方式是不行的
那么還可以用自定義指令 v-popover的方式實現博客園你啊347
但是elementUI文檔里面沒提到可以使用動態參數的方式設置v-popover:ref的值博客園你啊347
可以看到文檔里面 v-popover:popover是寫死上面組件ref的值的, 如果想要實現動態效果就得從這里下手
一般來說如果想要在element的組件屬性綁定動態參數(data里面的或者其他局部變量) 直接在變量前面加個冒號就好了 :src="`http://`+domain + suffix" 類似於這樣的
那么v-popover這個屬性按道理也可以, 只是文檔沒說具體寫法
下面就是最終實現方式了
點擊查看代碼
<div
class="item"
v-for="(item, index) in array.steps"
:key="index"
>
<el-popover
v-if="item.video && item.video !== ''"
placement="right"
title="步驟視頻"
trigger="hover"
注意這里ref參數的stepVideoRef是被單引號(ESC正下方那個按鍵), 解釋成字符串, 然后跟最外層for循環的index進行綁定, 形成不同的內容
:ref="`stepVideoRef` + index"
>
<video
:src="item.video"
controls="controls"
style="width: 400px; height: 300"
></video>
</el-popover>
<!--這里是用的是動態的自定義指令, 就是沒一個步驟對應的popover的索引都不一樣了, 因為是用index做了控制-->
<!--之后每一個popover的ref就是stepVideoRef0 stepVideoRef1 stepVideoRef2 stepVideoRef3 ... 這樣了-->
<div class="image" v-popover="`stepVideoRef` + index">
<el-image
:src="item.photo"
style="width: 100%; height: 100%"
fit="cover"
:z-index="2030"
>
</el-image>
</div>
</div>
以上就解決了el-popover循環動態自定義指令v-popover的需求
v-popover:refName 改成 v-popover="`refNameTemplate` + index" index可以任意變量, 但必須與ref保持一致
然后<el-popover :ref="`refNameTemplate` + index"> 和 v-popover指令的索引名稱保持一致即可
asdf博客園你啊347
的adf