Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vue动态绑定样式 #67

Open
TieMuZhen opened this issue Dec 14, 2021 · 0 comments
Open

Vue动态绑定样式 #67

TieMuZhen opened this issue Dec 14, 2021 · 0 comments
Labels

Comments

@TieMuZhen
Copy link
Owner

一、绑定类名方式

1、潜意识写法

首先,我们知道,如果想将js代码里面的东西渲染到dom元素属性上面,需用v-bind的方式绑定。 因此,我们首先想到的是下面这个写法:

<div id="app" >
    <div v-bind:class="myclass"></div>
</div>
new Vue({
    el:"#app",
    data:{
        myclass:"red"
    }
})

生成的结构是下面这样子

<div class="red"></div>

2、通过对象绑定

除了上面的写法,我们还可以这样写

<div id="app" >
    <div v-bind:class="{red : flag,active:false}"></div>
</div>
new Vue({
    el:"#app",
    data:{
        flag:true,
    }
})

生成的结构也是下面这样子

<div class="red"></div>

请注意两种写法的不同。第一种是通过v-binddata里面的值拿出来,第二种是把class绑定一个对象,通过这个对象里面的属性true/false来确定要渲染。

3、通过函数方法返回

当然在这里我们还可以通过函数方法计算返回对象属性:

<div v-bind:class="classObject"></div>
data: {
  isActive: true,
  error: null
},
computed: {
  classObject: function () {
    return {
      active: this.isActive && !this.error,
    }
  }
}

生成的结构也是下面这样子

<div class="active "></div>

4、利用数组的方式

我们也可以利用数组的方式添加多个样式 例如:

<div v-bind:class="[active, oactive]"></div>
data:{
    active:"red",
    oactive:"text-focus"
}

生成的结构也是下面这样子

<div class="red text-focus"></div>

注意 ,如果不加上左右两个中括号“[…]”,只会绑定第一个样式。 比如:

<div v-bind:class="active, oactive"></div>
data:{
    active:"red",
    oactive:"text-focus"
}

生成的结构也是下面这样子

<div class="red"></div>

二、绑定内联样式

和我们绑定到类名的方式差不多,通过style添加的内联样式,可以不用写浏览器引擎的前缀,比如-webkit-trasform,vue会自己检测并自动添加上去

1、从data里面直接取出来

<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
data: {
  activeColor: 'red',
  fontSize: 30
}

2、从一个对象取出来

<div v-bind:style="styleObject"></div>
data: {
  styleObject: {
    color: 'red',
    fontSize: '13px'
  }
}

3、从多个对象取出来

<div v-bind:style="[baseStyles, overridingStyles]"></div>
data: {
  baseStyles: {
    color: 'red',
    fontSize: '13px'
  },
  overridingStyles{
      background:'red'
  }
}

三、在组件上绑定样式

其实也是和在dom元素上面绑定样式差不多。来看官方文档里面的写法:

Vue.component('my-component', {
  template: '<p class="foo bar">Hi</p>'
})
<my-component class="baz boo"></my-component>

结果是这样子的

<p class="foo bar baz boo">Hi</p>

参考文献

@TieMuZhen TieMuZhen added the Vue label Dec 14, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant