10

一个 1 分钟就学会的 vue 小技巧(真的一看就会)

 3 years ago
source link: https://zhuanlan.zhihu.com/p/342977625
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

一个 1 分钟就学会的 vue 小技巧(真的一看就会)

关注微信公众号:web前端学习圈,领取85G前端全套系统教程

一、内容简介

在使用vue开发时,经常会封装很多的组件方便复用,那么难免就有写样式相关组件,比如需要使用时传入颜色、高度等样式参数。
那么问题来了:我们要怎么在样式中使用组件中接收的参数呢?或者说,我们要怎么在样式中使用data中的变量呢?

二、代码演示

这个用法真的简单,没什么其他的知识点,直接上代码:

<template>
  <div class="box" :style="styleVar">
  </div>
</template>
<script>
export default {
  props: {
    height: {
      type: Number,
      default: 54,
    },
  },
  computed: {
    styleVar() {
      return {
        '--box-height': this.height + 'px'
      }
    }
  },
}
</script>
<style scoped>
.box {
  height: var(--box-height);
}
</style>

这样我们就在vue中实现了在样式里使用js变量的方法:
及通过css定义变量的方式,将变量在行内注入,然后在style中使用var()获取我们在行内设置的数据即可。

三、最后

以后,在封装一些需要动态传入样式参数的ui组件是不是简便了不少。你学会了么?赶快在项目中尝试一下吧~~

原作者姓名: liangyue
原出处:掘金
原文链接:分享一个一分钟就学会的vue小技巧(真的一看就会~~)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK