• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Vue.2.0.5实现Class 与 Style 绑定的实例

vue 搞代码 4年前 (2022-01-08) 13次浏览 已收录 0个评论

本文来源gao@daima#com搞(%代@#码网@篇文章主要介绍了Vue.2.0.5实现Class 与 Style 绑定的实例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

Class 与 Style 绑定

数据绑定一个常见需求是操作元素的 class 列表和它的内联样式。因为它们都是属性 ,我们可以用v-bind 处理它们:只需要计算出表达式最终的字符串。不过,字符串拼接麻烦又易错。因此,在 v-bind 用于 class 和 style 时, Vue.js 专门增强了它。表达式的结果类型除了字符串之外,还可以是对象或数组。

绑定 HTML Class

对象语法

我们可以传给 v-bind:class 一个对象,以动态地切换 class 。

 <div></div>

上面的语法表示 classactive 的更新将取决于数据属性 isActive 是否为真值 。

我们也可以在对象中传入更多属性用来动态切换多个 class 。此外, v-bind:class 指令可以与普通的 class 属性共存。如下模板:

 <div class="static"> </div>

如下 data:

 data: { isActive: true, hasError: false }

渲染为:

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

当 isActive 或者 hasError 变化时,class 列表将相应地更新。例如,如果 hasError的值为 true , class列表将变为 “static active text-danger”。

你也可以直接绑定数据里的一个对象:

 <div></div>
 data: { classObject: { active: true, 'text-danger': false } }

渲染的结果和上面一样。我们也可以在这里绑定返回对象的计算属性。这是一个常用且强大的模式:

 <div></div>
 data: { isActive: true, error: null }, computed: { classObject: function () { return { active: this.isActive && !this.error, 'text-danger': this.error && this.error.type === 'fatal', } } }

数组语法

我们可以把一个数组传给 v-bind:class ,以应用一个 class 列表:

 <div>
 data: { activeClass: 'active', errorClass: 'text-danger' }

渲染为:

 <div class="active text-danger"></div>

如果你也想根据条件切换列表中的 class ,可以用三元表达式:

 <div>

此例始终添加 errorClass ,但是只有在 isActive 是 true 时添加 activeClass 。

不过,当有多个条件 class 时这样写有些繁琐。可以在数组语法中使用对象语法:

 <div>

With Components

This section assumes knowledge ofVue Components. Feel free to skip it and come back later.

When you use the class attribute on a custom component, those classes will be added to the component’s root element. Existing classes on this element will not be overwritten.

For example, if you declare this component:

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

Then add some classes when using it:

 

The rendered HTML will be:

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

The same is true for class bindings:

 

When isActive is truthy, the rendered HTML will be:

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

绑定内联样式

对象语法

v-bind:style 的对象语法十分直观――看着非常像 CSS ,其实它是一个 JavaScript 对象。 CSS 属性名可以用驼峰式(camelCase)或短横分隔命名(kebab-case):

 <div></div>
 data: { activeColor: 'red', fontSize: 30 }

直接绑定到一个样式对象通常更好,让模板更清晰:

 <div></div>
 data: { styleObject: { color: 'red', fontSize: '13px' } }

同样的,对象语法常常结合返回对象的计算属性使用。

数组语法

v-bind:style 的数组语法可以将多个样式对象应用到一个元素上:

 <div>

自动添加前缀

当 v-bind:style 使用需要特定前缀的 CSS 属性时,如 transform ,Vue.js 会自动侦测并添加相应的前缀。

以上就是Vue.2.0.5实现Class 与 Style 绑定的实例的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Vue.2.0.5实现Class 与 Style 绑定的实例

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址