CSS-flex布局

在Flexbox布局中,当子元素同时设置了:

  • 显式高度(如height: 30px

  • flex属性(如flex: 1

flex属性会覆盖显式的高度设置。浏览器会优先遵循flex属性的分配规则。

<div style="display: flex; flex-direction: column;">

        <div style="height: 30px;  flex: 1;"></div>
        <div style="flex:6;"></div>

</div> 

在 flex-direction: row(默认值)的Flexbox布局中:

  • 子元素同时设置了 width: 30px 和 flex: 1

  • flex属性会覆盖显式的宽度设置

  • 浏览器会优先遵循flex属性的分配规则

<div style="display: flex;">

        <div style="width : 30px;  flex: 1;"></div>
        <div style="flex:6;"></div>

</div> 

想要在弹性盒子内设置第一个盒子的高度(宽度同理),可以将第一个盒子不设置flex属性,在剩下的盒子中设置flex:1属性

<div style="display: flex; flex-direction: column;">
    
   <div style="height: 30px;">内部元素高度30px</div>

   <div style="flex:1;"></div>

</div>

如果弹性盒子内的子模块有多个,可以将第一个设置固定高度,其余盒子在包装在一个div内再作为一个弹性盒子。--- 这是一个很经典的嵌套Flexbox布局

布局效果

  • 子模块1:固定高度30px

  • 子模块2、3、4的容器:占据剩余所有空间

  • 子模块2、3、4:在弹性容器内可以进一步自定义布局

<div style="display: flex; flex-direction: column;">
    
   <div style="height: 30px;"> 子模块1:内部元素高度30px </div>

   <div style="flex:1; display: flex; flex-direction: column;">
        <div> 子模块2 </div>
        <div> 子模块3 </div>
        <div> 子模块4 </div>
   </div>

</div>

JavaScript 箭头函数陷阱

错误写法:{ store.state.isCollapse }执行了,但是没有返回

const isCollapse = computed(() => { store.state.isCollapse })

正确写法:

const isCollapse = computed(() => store.state.isCollapse)

const isCollapse = computed(() => {
    return store.state.isCollapse
})

VUE3知识点

computed计算属性:

person.fullName = computed({
  get() {
    // 仍然监听 firstname 和 lastname,这两变化,fullName 变化
    return person.firstname + '-' + person.lastname
  },
  set(value) {
    // 当外部修改 fullName 时,反向更新它的依赖项firstname 和lastname 
    const nameArr = value.split('-')
    person.firstname = nameArr[0]  // 这里会触发 getter 重新计算
    person.lastname = nameArr[1]   // 这里也会触发 getter 重新计算
  }
})

// 使用示例
fullName.value = '王-五'  
// 执行 setter → 更新 firstname 和 lastname
// firstname/lastname 变化 → 触发 getter 重新计算
// getter 返回新的 "王-五"

computed注重的计算出来的值(回调函数的返回值),所以必须要写返回值。

而watchEffect更注重的是过程(回调函数的函数体),所以不用写返回值。

watchEffect所指定的回调中用到的数据只要发生变化,则重新执行回调

watch属性
监视reactive所定义的一个响应式数据的全部属性,

此处无法正确获得oldValue

强制开启了深度监视(deep配置无效)

// 情况三:监视reactive所定义的一个响应式数据,此处无法正确获得oldValue
watch(person,(newValue,oldValue)=>{
  console.log('person变化了',newValue,oldValue);
})

监视reactive所定义的一个响应式数据的某个属性

watch(()=>person.name,(newValue,oldValue)=>{
  console.log('person变化了',newValue,oldValue);
})

监视reactive所定义的一个响应式数据中的某些属性

watch(()=>person.name,()=>person.age,(newValue,oldValue)=>{
  console.log('person变化了',newValue,oldValue);
})

此处由于是监视的是reactive所定义的对象中的某个属性,所以deep配置有效

watch(()=>person.job,(newValue,oldValue)=>{
  console.log('person变化了',newValue,oldValue);
},{deep:true})

两个小坑
监视reactive定义的响应式数据时:
oldValue无法正确获取,强制开启了深度监听(deep配置失效)
监视reactive定义的响应式数据中某个属性时,deep配置有效
 

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐