目標
使用vue2.0實現(xiàn)自定義彈窗指令,當標簽有該指令時,點擊標簽可以彈出彈窗

實現(xiàn)
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script></head><body> <div id="app"> <button id="btn" v-popup="{text: '這是一個自定義的彈窗'}">點擊我彈窗哈哈哈</button> <div id="d"></div> </div> <script> Vue.directive('popup', { inserted: function (el, binding) { // console.log(binding.value.text) var o = el; var myDiv = document.createElement('div'); myDiv.style.width = '300px'; // myDiv.style.height = '130px'; myDiv.style.position = 'fixed'; myDiv.style.top = '50%'; myDiv.style.left = '50%'; myDiv.style.transform = 'translate(-50%, -100%)'; myDiv.style.zIndex = '100'; myDiv.style.backgroundColor = '#f3f5f8'; myDiv.style.display = 'none'; myDiv.style.textAlign = 'center'; myDiv.style.paddingTop = '15px' myDiv.style.borderRadius = '5px'; myDiv.style.borderWidth = '1px'; myDiv.style.borderStyle = 'solid'; myDiv.style.borderColor = '#696969'; var myContent = document.createElement('p'); var myText = document.createTextNode(binding.value.text); var btnWrapper = document.createElement('div') btnWrapper.style.marginTop = '20px' btnWrapper.style.marginBottom = '20px' var myConfirm = document.createElement('input'); myConfirm.type = 'button'; myConfirm.value = '確定'; myConfirm.style.marginRight = '15px' var myCancel = document.createElement('input'); myCancel.type = 'button'; myCancel.value = '取消'; btnWrapper.appendChild(myConfirm) btnWrapper.appendChild(myCancel) myDiv.appendChild(myContent.appendChild(myText)) myDiv.appendChild(btnWrapper) document.body.appendChild(myDiv); o.onclick = function (event) { myDiv.style.display = 'block' } myConfirm.onclick = function (event) { myDiv.style.display = 'none' } myCancel.onclick = function (event) { myDiv.style.display = 'none' } } }) var vm = new Vue({ el: '#app', data:{ } }) </script></body></html>總結
以上所述是小編給大家介紹的Vue自定義彈窗指令的實現(xiàn)代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網(wǎng)網(wǎng)站的支持!
新聞熱點
疑難解答