首页 > 解决方案 > 在 vuejs 中获取 scroped CSS 属性的最可靠方法是什么?

问题描述

在 vuejs 中,元素被分配了一个以 'data-v-***' 开头的属性

我找不到任何有关获取此值的文档,因此最终使用了 refs 并获取了主节点的属性:

<template>
  <div class="m-colour-picker" ref="thisContainer">
  ...
  </div>
</template>
    const attributes = this.$refs.thisContainer.getAttributeNames();
    let dataAttribute = '';
    attributes.forEach((attribute: string) => {
      if (attribute.substring(0, 5) === 'data-') {
        dataAttribute = attribute;
      }
    });

但是感觉有点强迫..vue中有没有一种方法可以获取这个已经内置的?

标签: vue.jsvuejs2

解决方案


这与 Vue.js 关系不大。任何元素的数据属性都会自动与其内部dataset对象同步。

例子:

console.log(foobar.dataset);

console.log(foobar.dataset.vFoo);
console.log(foobar.dataset.vBar);

// notice how data attributes containing more than the initial data- dash
// are automatically transformed to camel case:
// data-v-foo-bar ===> dataset.vFooBar
console.log(foobar.dataset.vFooBar);

// if all you care about is the names of the attributes:
console.log(Object.keys(foobar.dataset));
<div id="foobar" data-v-foo="bar" data-v-bar="baz" data-v-foo-bar="foobaz"></div>


推荐阅读