Vue自定義複製指令 v-copy功能的實現
阿新 • • 發佈:2022-01-10
使用自定義指令建立一個點選複製文字功能
1. 建立v-copy.檔案
import from "vue"; // 註冊一個全域性自定義複製指令 `v-copy` Vue.directive("copy",{ bind(el,{ value }) { el.$value = value; el.handler = () => { el.style.position = 'relative'; if (!el.$value) { // 值為空的時候,給出提示 alert('無複製內容'); return } // 動態建立 textarea 標籤 const textarea = document.createElement('textarea'); // 將該 textarea 設為 readonly 防止 iOS 下自動喚起鍵盤,同時將textarea 移出可視區域 textarea.readOnly = 'readonly'; textarea.style.position = 'absolute'; textarea.style.top = '0px'; textarea.style.left = '-9999px'; textarea.style.zIndex = '-9999'; // 將要 copy 的值賦給 textarea 標籤的 value 屬性 textarea.value = el.$value // 將 textarea 插入到 el 中 el.appendChild(textarea); // 相容IOS 沒有 select() 方法 if (textarea.createTextRange) { textarea.select(); // 選中值並複製 } else { textarea.setSeWNRghrkvlectionRange(0,el.$value.length); textarea.focus(); } const result = document.execCommand('Copy'); if (result) alert('複製成功'); el.removeChild(textarea); } el.addEventListener('click',el.handler); // 繫結點選事件 },// 當傳進來的值更新的時候觸發 componentUpdated(el,{ value }) { el.$value = value; },// 指令與元素解綁的時候,移除事件繫結 unbind(el) { el.removeEventListener('click',el.handler); },});
2. 引入v-copy
// main.js 根據檔案的相關路徑引入v-copy.js檔案 import "xx/v-copy.js"; // v-copy 指令
3. 在標籤使用v-copy
<span v-copy="複製內容">複製</span>
補充:Vue 自定義指令合集 (文字內容複製指令 v-copy)
我們常常在引入全域性功能時,主要都是寫於 js 檔案、元件中。不同於他們在使用時每次需要引用或註冊,在使用上指令更加簡潔。
今天主要實現的是一個複製文字指令*v-copy
*,其中主要的引數有兩個icon
和dblclick
引數 | 說明 |
---|---|
dblclick | 雙擊複製 |
icon | 新增icon複製按鈕,單擊按鈕實現複製 |
程式碼如下:
bind(el,binding) {
if (binding.modifiers.dblclick) {
el.addEventListener("dblclick",() => handleClick(el.innerText));
el.style.cursor = "copy";
} else if (binding.modifiers.icon) {
el.addEventListener("mouseover",() => {
if (el.hasicon) return;
const icon = document.createElement("em");
icon.setAttribute("class","demo");
icon.setAttribute("style","{margin-left:5px,color:red}");
icon.innerText = "複製";
el.appendChild(icon);
el.hasicon = true;
icon.addEventListener("click",() => handleClick(el.innerText));
icon.style.cursor = "pointer";
});
el.addEventListener("mouseleave",() => {
let em = el.querySelector(客棧"em");
el.hasicon = false;
el.removeChild(em);
});
} else {
el.addEventListener("click",() => handleClick(el.innerText));
el.style.cursor = "copy";
}
function handleClick(content) {
if (Window.clipboardData) {
window.Clipboard.setData("text",content);
return;
} else {
(function(content) {
document.oncopy = function(e) {
e.clipboardData.setData("text",content);
e.preventDefault();
document.oncopy = null;
};
})(content);
document.execCommand("Copy");
}
}
},
到此這篇關於Vue自定義複製指令 v-copy功能的實現的文章就介紹到這了,更多相關Vue複製指令 v-copy內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!