vue设置样式

vue设置样式

2.1.1 样式在标签中的使用

内联方式:

内联方式有以下几种形式:

//html
<div id="app">
    <h2 :style="{'background-color': 'green'}">test1</h2>
    <h2 :style="styleObj1">test2</h2>
    <h2 :style="[styleObj1,styleObj2]">test3</h2>
</div>

//js
    new Vue({
        el: "#app",
        data: {
            msg: "hello",
            isActive: true,
            styleObj1: {'background-color': 'green' },
            styleObj2: {'font-size': '100px' },
        },
        methods: {

        }
    });

注意:如果属性带有横线“-”,则此属性必须用冒号引起来;

分离方式:

  • 数组形式
  • 数组里使用三元表达式
  • 数组里使用对象
  • 对象的形式
    <!-- css -->
    <style>
        .green {
            background-color: green;
        }
        .big {
            font-weigth: 200;
        }
        .active {
            letter-spacing: 0.5em;
        }
    </style>

    <!-- html 分离方式的使用-->
    <div id="app">
        <h2 :class="['green', 'big']">test1</h2>
        <h2 :class="['green', 'big', isActive?'active':'']">test2</h2>
        <h2 :class="['green', 'big', {'active': isActive}]">test3</h2>
        <h2 :class="{ green:true, big:true }">test4</h2>
        <h2 :class="classObj">test5</h2>
    </div>

    <!-- vue -->
    <script>
        new Vue({
        el: "#app",
        data: {
            msg: "hello",
            isActive: true,
            classObj: { green:true, big:true }
        },
        methods: {

        }
    });
    </script>

2.1.2 样式的引入

css样式可以直接设置class和引入css文件的形式

组件中直接设置class的形式

<template>
    <div>
        <p class="green">绿色</p>
    </div>
</template>

<script>
</script>

<!-- 直接在此处设置 -->
<style>
    .green {
        background-color: green;
    }
</style>

引入css文件的方式:

  • 在main.js中引入:

    这种写法适用于此css文件存在于项目中,不适用于通过网址访问的方式引入,会报错。

import 'element-ui/lib/theme-default/index.css'
  • 在组件中引入:

方法一:

<script>
    import '../static/css/global.css' /*引入公共样式*/
</script>

方法二:

<style scoped >

 @import './../static/css/global.css'; /*引入公共样式*/
 @import "../css/style.css";

/* 注意:
    1、引入语句后面最好加上分号,只引用一个还好,引用多个不加分号会报错。 
    2、使用: @import
*/
</style>

方法三:

<style scoped src="../static/css/user.css">
</style>

2.1.3 样式的作用域

import进来的css是全局的;

组件中的style没有添加scoped,样式也是全局的,如:

<style>
    .h1{
        color:red;
    }
</style>

想要组件的样式私有化,就要添加scoped,如:

<style scoped>  
    /* 添加scoped后,此处的样式只是针对此组件的,不会污染全局 */
    .h1{
        color:red; 
    }
</style>

注意: 使用 scoped 后,父组件的样式将不会渗透到子组件中。想要在子组件中重新设置父组件的样式,可以使用深度作用选择器 /deep/,如:

<style scoped>
    /deep/ .text-box input {
        width: 166px;
    }
 </style>

2.1.4 css预处理器的使用

在style标签上设置属性lang的值,如:lang="less"

<style lang="less" scoped>
    .text-box {
        input {
            width: 166px;
        }
    }
 </style>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容