Vue设置div的宽度和高度

本文介绍如何使用Vue.js和ECharts创建响应式动态图表,包括动态调整图表大小以适应不同屏幕尺寸,以及通过Ajax获取数据实时更新图表内容。

html代码

          <div id="divOrganization" v-bind:style="{width:EchartsWidth,height: EchartsHeight,position:'absolute' }"  >

            </div>

js代码        

new Vue({
            el: '#app',
            data: { 
                EchartsHeight: (document.body.clientHeight - 140 )+'px',
                EchartsWidth:(document.body.clientWidth - 260)+'px',// (screen.width-250)*0.96+'px',
                //return {
                //    info: null
                //}
            },

 

<script src="~/Content/AdminLTE-3.0.1/plugins/jquery/jquery.min.js"></script>
<script src="../Scripts/echarts.js"></script>
<script src="~/Content/plugins/vue-dev/dist/vue.js"></script>
<script src="~/Content/plugins/axios-master/dist/axios.js"></script> 

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
}

<div class="content">
    <div class="row" id="app">
            <div id="divOrganization" v-bind:style="{width:EchartsWidth,height: EchartsHeight,position:'absolute' }"  >

            </div>
 </div>
 </div>

<script type="text/javascript">
    var IsSetOrganization = false;

    $(function () {

        new Vue({
            el: '#app',
            data: { 
                EchartsHeight: (document.body.clientHeight - 140 )+'px',
                EchartsWidth:(document.body.clientWidth - 260)+'px',// (screen.width-250)*0.96+'px',
                //return {
                //    info: null
                //}
            },
            mounted() {
                var token = $('*[name="__RequestVerificationToken"]').val();
                var ID = '1000';
                var ParentID = '0';
                this.GetOrganization(token,ID,ParentID);
            },
            computed: {
                //// 计算属性的 getter
                //EchartsHeight: function () {
                //    // `this` 指向 vm 实例
                //    return screen.height;
                //}, 
                //EchartsWidth: function () {
                //    // `this` 指向 vm 实例
                //    return screen.width;
                //}
            },
            methods: { 
                GetOrganization: function () {
                    var data = "";

                    var myChartOrganization = echarts.init(document.getElementById('divOrganization'));
                    var labelOption = {
                        normal: {
                            show: true,

                            formatter: '{c}  {name|{a}}',
                            fontSize: 16,
                            rich: {
                                name: {
                                    textBorderColor: '#fff'
                                }
                            }
                        }
                    };

                    // 指定图表的配置项和数据
                    var option2 = {
                        // backgroundColor: '#DEF',//'#0f375f',
                        graphic: [
                            {
                                type: 'image',
                                id: 'logo',
                                //right: '11',
                                //bottom: '28%',
                                //z: 1000,
                                bounding: 'raw',
                                style: {
                                    image: '../image/background3.jpg',
                                    width: screen.width,//1545,
                                    height: screen.height,
                                }
                            }
                        ],
                        tooltip: {
                            show: IsSetOrganization,
                            trigger: 'item',
                            triggerOn: 'mousemove',//mousemove|
                            enterable: true,
                            formatter: function (params) {
                         

                                return html;
                            },
                        },

                        toolbox: {
                            show: false,
                            feature: {
                                mark: { show: true },
                                dataView: { show: true, readOnly: false },
                                magicType: { show: true, type: ['line', 'bar'] },

                            }
                        },

                        series: [
                            {
                                type: 'tree',

                                data: [data],

                                left: '2%',
                                right: '2%',
                                top: '8%',
                                bottom: '20%',

                                symbol: 'image://http://' + window.location.host + '/image/Dark_blue_button.png',//'emptyCircle',
                                symbolSize: [100, 30],
                                orient: 'vertical',

                                expandAndCollapse: false,
                                initialTreeDeptp: -1,
                                itemStyle: {
                                    color: '#FFF',//'#f56954',
                                    borderColor: "#00c0ef",
                                    borderWidth: 8,
                                },
                                label: {
                                    formatter: '{b} \n {c}  ',
                                    position: 'inside',
                                    distance: 5,
                                    fontSize: 12,
                                    color: "#FFF",
                                },

                                leaves: {
                                    label: {
                                        position: 'inside',
                                        // rotate: -90,
                                        verticalAlign: 'middle',
                                        align: 'center',
                                    },
                                    itemStyle: {
                                        color: "#FFF",//"#00c0ef",
                                    }

                                },

                                animationDurationUpdate: 750
                            }
                        ]              //  color: ['#007bff', '#dc3545','#2E90CD', '#FE0000']
                    };

                    // 使用刚指定的配置项和数据显示图表。

                    myChartOrganization.showLoading(); // 加载动画

                    myChartOrganization.setOption(option2);

                    myChartOrganization.hideLoading();

                    GetChartResult();

                    function GetChartResult() {
                        var token = $('*[name="__RequestVerificationToken"]').val();
                        var ID = '1000';
                        var ParentID = '0';
                        var auto = myChartOrganization.getOption();

                        axios({
                            method: 'post',
                            url: '/BaseData/GetOrganization',

                            transformRequest: [
                                function (data) {
                                    let ret = ''
                                    for (let it in data) {
                                        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                                    }
                                    ret = ret.substring(0, ret.lastIndexOf('&'));
                                    return ret
                                }
                            ],
                            data: {
                                __RequestVerificationToken: token,
                                ID: ID,
                                ParentID: ParentID,
                                //OrganizationName: 'easyboot'
                            }
                        })
                            .then(function (response) {
                                console.log(response)
                                console.log(response.data)
                                var auto = myChartOrganization.getOption();

                                var data1 = response.data.replace(/ID/g, "value").replace(/OrganizationName/g, "name").replace(/CHILDREN/g, "children")
                                var data2 = data1.substring(0, data1.length - 1);
                                var data3 = data2.substring(1, data1.length);

                                var objData = JSON.parse(data1)

                                auto.series[0].data = objData; //数据源
                                //auto.legend.data =legendData;
                                myChartOrganization.showLoading(); // 加载动画
                                myChartOrganization.setOption(auto, false);
                                myChartOrganization.hideLoading();
                            });



                        @*$.ajax({
                            type: 'POST',
                            url: '@Url.Action("GetOrganization")',

                            data: {
                                ID: ID,
                                ParentID: ParentID,
                                __RequestVerificationToken: token,
                            },
                            async: false,

                            dataType: "json",
                            success: function (data) {
                                //console.log(data)

                                var auto = myChartOrganization.getOption();

                                var data1 = data.replace(/ID/g, "value").replace(/OrganizationName/g, "name").replace(/CHILDREN/g, "children")
                                var data2 = data1.substring(0, data1.length - 1);
                                var data3 = data2.substring(1, data1.length);

                                var objData = JSON.parse(data1)

                                auto.series[0].data = objData; //数据源
                                //auto.legend.data =legendData;
                                myChartOrganization.showLoading(); // 加载动画
                                myChartOrganization.setOption(auto, false);
                                myChartOrganization.hideLoading();
                            },
                            error: function (message) {
                                // alert(message);
                            }
                        });*@
                    }
                },
                SetDataImportTableName: function () {
                    localStorage.setItem('DataImportTableName', 'organization')
                }
            }
        }) 

    });
</script>

 

 

<think>我们正在讨论Vue2中实现div自适应宽度的方法。根据引用[3],用户提到了一个使用拖拽分割线实现自适应布局的例子。但用户现在想要的是div自适应宽度,可能不需要拖拽功能。我们可以考虑以下几种方法: 1. 使用CSS Flexbox布局实现自适应宽度 2. 使用CSS Grid布局 3. 使用百分比宽度 4. 结合Vue动态计算宽度(响应窗口变化) 由于引用[2]中提到了全局自适应,我们可以利用Vue监听窗口大小变化,动态设置div宽度。 ### 方法1:使用Flex布局(最简单常用) 在父容器上设置`display: flex`,子元素会自动填充剩余空间。 ```html <template> <div class="container"> <div class="sidebar">侧边栏(固定宽度)</div> <div class="main-content">主内容(自适应宽度)</div> </div> </template> <style scoped> .container { display: flex; height: 100vh; } .sidebar { width: 200px; /* 固定宽度 */ background: #f0f0f0; } .main-content { flex: 1; /* 自适应剩余宽度 */ background: #e0e0e0; overflow: auto; /* 内容超出出现滚动条 */ } </style> ``` ### 方法2:使用Grid布局 ```html <template> <div class="container"> <div class="sidebar">侧边栏</div> <div class="main-content">主内容</div> </div> </template> <style scoped> .container { display: grid; grid-template-columns: 200px 1fr; /* 第一列固定200px,第二列自适应 */ height: 100vh; } .main-content { overflow: auto; } </style> ``` ### 方法3:使用百分比宽度(需要知道父容器宽度) ```html <template> <div class="container"> <div class="sidebar">侧边栏</div> <div class="main-content">主内容</div> </div> </template> <style scoped> .container { width: 100%; height: 100vh; } .sidebar { width: 200px; float: left; background: #f0f0f0; height: 100%; } .main-content { width: calc(100% - 200px); /* 减去侧边栏宽度 */ float: left; height: 100%; background: #e0e0e0; overflow: auto; } </style> ``` ### 方法4:动态计算宽度(响应式) 如果需要更复杂的自适应逻辑(如根据窗口大小改变布局),可以在Vue中监听窗口大小变化,动态计算宽度。 ```html <template> <div class="container"> <div class="sidebar" :style="{ width: sidebarWidth + 'px' }">侧边栏</div> <div class="main-content" :style="{ width: mainWidth + 'px' }">主内容</div> </div> </template> <script> export default { data() { return { sidebarWidth: 200, windowWidth: 0 } }, computed: { mainWidth() { return this.windowWidth - this.sidebarWidth; } }, mounted() { this.windowWidth = window.innerWidth; window.addEventListener('resize', this.handleResize); }, beforeDestroy() { window.removeEventListener('resize', this.handleResize); }, methods: { handleResize() { this.windowWidth = window.innerWidth; } } } </script> <style scoped> .container { display: flex; /* 或者使用浮动等,这里用flex确保布局 */ height: 100vh; } .sidebar { background: #f0f0f0; } .main-content { background: #e0e0e0; overflow: auto; } </style> ``` ### 注意事项 - 对于大多数布局,推荐使用Flex或Grid,它们更现代且易于维护。 - 如果需要在Vue中动态改变布局(例如通过按钮切换侧边栏的显示/隐藏),可以结合使用计算属性CSS类。 - 在组件销毁前,务必移除事件监听器,避免内存泄漏。 ### 响应式设计补充 根据引用[2]中提到的全局自适应,我们还可以使用媒体查询来适配不同屏幕,但通常媒体查询用于断点布局,而上述方法可以连续自适应。 ### 相关问题 §§相关问题§§ 1. Vue2中如何实现高度自适应布局? 2. 如何在Vue2中实现拖拽调整div宽度? 3. Vue2项目如何同时适配PC移动端? </think>在 Vue2 中实现 div 自适应宽度主要涉及 CSS 布局技术 Vue 响应式编程的结合使用。以下是几种效实用的解决方案: ### 1. Flex 弹性布局(推荐方案) ```html <template> <div class="container"> <div class="fixed-width">左侧固定宽度(200px)</div> <div class="auto-width">右侧自适应宽度区域</div> </div> </template> <style scoped> .container { display: flex; /* 启用弹性布局 */ height: 100vh; } .fixed-width { width: 200px; /* 固定宽度 */ background: #f0f0f0; } .auto-width { flex: 1; /* 关键属性 - 自动填充剩余空间 */ background: #e0e0e0; overflow: auto; /* 内容超出自动滚动 */ } </style> ``` **实现原理**: - `display: flex` 创建弹性容器 - `flex: 1` 使元素自动填充剩余空间[^3] - 响应式适应父容器尺寸变化 ### 2. CSS Grid 网格布局 ```html <template> <div class="grid-container"> <div class="fixed-col">固定列(200px)</div> <div class="fluid-col">自适应列</div> </div> </template> <style scoped> .grid-container { display: grid; grid-template-columns: 200px 1fr; /* 1fr单位自动分配剩余空间 */ height: 100vh; } .fluid-col { overflow: auto; } </style> ``` ### 3. 百分比计算宽度(传统方法) ```html <template> <div class="wrapper"> <div class="sidebar">侧边栏(20%)</div> <div class="content">主内容区域(80%)</div> </div> </template> <style scoped> .wrapper { display: flex; height: 100vh; } .sidebar { width: 20%; } .content { width: 80%; /* 或使用 calc(100% - 200px) */ } </style> ``` ### 4. 响应式动态计算(Vue + JS) ```html <template> <div ref="container" class="dynamic-container"> <div class="static-block">固定块(300px)</div> <div class="dynamic-block" :style="{ width: dynamicWidth + 'px' }"> 动态宽度区域 </div> </div> </template> <script> export default { data() { return { dynamicWidth: 0 } }, mounted() { this.updateWidth(); window.addEventListener('resize', this.updateWidth); }, beforeDestroy() { window.removeEventListener('resize', this.updateWidth); }, methods: { updateWidth() { const containerWidth = this.$refs.container.offsetWidth; this.dynamicWidth = containerWidth - 300; // 减去固定块宽度 } } } </script> <style scoped> .dynamic-container { display: flex; width: 100%; height: 300px; } .static-block { width: 300px; background: #eee; } .dynamic-block { background: #ddd; overflow: auto; } </style> ``` ### 5. 嵌套滚动容器实现 ```html <template> <div class="scroll-wrapper"> <div class="header">顶部固定区域</div> <div class="scroll-content"> <div class="left-panel">左侧面板(固定300px)</div> <div class="auto-scroll"> <!-- 自适应宽度滚动区 --> <div v-for="i in 50" :key="i">内容项 {{i}}</div> </div> </div> <div class="footer">底部固定区域</div> </div> </template> <style scoped> .scroll-wrapper { height: 100vh; display: flex; flex-direction: column; } .header, .footer { height: 60px; background: #ccc; } .scroll-content { flex: 1; display: flex; overflow: hidden; } .left-panel { width: 300px; background: #f5f5f5; } .auto-scroll { flex: 1; overflow: auto; /* 关键:自适应宽度+溢出滚动 */ } </style> ``` ### 关键实现要点 1. **布局选择**: - 优先使用 Flex/Grid 等现代布局方案 - 传统方案使用 `calc(100% - 固定宽度)` 2. **滚动处理**: ```css .auto-width { overflow: auto; /* 横向/纵向自动滚动 */ overflow-x: auto; /* 仅横向滚动 */ } ``` 3. **响应式断点**(结合引用[2]): ```css @media (max-width: 768px) { .container { flex-direction: column; } .fixed-width { width: 100%; } } ``` 4. **性能优化**: - 使用 `will-change: transform` 提升滚动性能 - 避免在 resize 事件中频繁触发重排 - 使用防抖函数控制 resize 事件频率 > **最佳实践**:绝大多数场景推荐使用 Flexbox 方案(方案1),它提供最简洁的实现最佳的浏览器兼容性[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值