【问题标题】:What is the most reliable way to fetching the scroped CSS attribute in vuejs?在 vuejs 中获取 scroped CSS 属性的最可靠方法是什么?
【发布时间】:2021-06-20 22:26:35
【问题描述】:

在 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.js vuejs2


    【解决方案1】:

    这与 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));
    &lt;div id="foobar" data-v-foo="bar" data-v-bar="baz" data-v-foo-bar="foobaz"&gt;&lt;/div&gt;

    【讨论】:

    猜你喜欢
    • 2016-07-31
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多