vue 監聽頁面 元素寬度和高度(我值監聽了寬度) 變化
插件安裝 element-resize-detector
npm install element-resize-detector
引入插件
要是有用餓了么UI框架的話,這個都不用引入
<script>
import elementResizeDetectorMaker from "element-resize-detector";
</script>
注冊局部自定義指令

directives: {
// 使用局部注冊指令的方式
resize: {
// 指令的名稱
bind(el, binding, vnode) {
// el為綁定的元素,binding為綁定給指令的對象
let width = "";
// let height = ""; 這就是監聽高度了
let that = vnode.context;
function isReize() {
const style = document.defaultView.getComputedStyle(el);
// if (width !== style.width||height !== style.height) { 這就是監聽寬度和高度了
if (width !== style.width) {
// binding.value(); // 關鍵
let pxNumber = style.width.split("px")[0];
that[binding.arg](binding.value, pxNumber);
}
width = style.width;
// height = style.height; 這就是監聽寬度和高度了
}
el.__vueSetInterval__ = setInterval(isReize, 300);
},
unbind(el) {
clearInterval(el.__vueSetInterval__);
},
},
},
行間綁定 (綁定要監聽的元素)
<div v-resize:resize="{
className: index + 'titleContent',
}"></div>
事件操作 (元素寬度改變時執行的事件)
/**
* @description: 監聽寬度的改變事件 自定義指令 CDMB0000212titleContent
* @param {*} value
* @param {*} width
* @return {*}
*/
resize(value, width) {
//value 這個是傳進來的參數的對象 //{className:"0000titleContent"} 上面的變量index值是0000
// width是寬度的值
if (value && value.className) {
if (width < 800) {
//$("." + value.className).hide();
} else {
//$("." + value.className).show();
}
}
}