get v-id-xx value for scoped css on Vue Single File Component
Asked Answered
H

2

7

When adding elements via pure js on Vue Single File Component, the added elements don't have v-id-xx attribute for scoped css.

How can I get THE component's v-id-hash value by pure js?

Hugibert answered 19/4, 2018 at 11:23 Comment(0)
C
14

The scoped-style data ID is added to the component instance as:

this.$options._scopeId // returns something like 'data-v-763db97b'

This way you could add it as attribute using:

somElement.setAttribute(this.$options._scopeId, "");

Here's a CodeSandbox demo showing an example.

Cariecaries answered 19/4, 2018 at 16:34 Comment(0)
M
1

In a Vue 3 directive, we can get the component's scope ID using the binding parameter available in directive lifecycle hooks.

Example:

In mounted hooks:

mounted(el, binding, vnode, prevVnode) {
  const span = document.createElement("span");
  console.log("scope_id", binding.instance.$options.__scopeId);
  span.setAttribute(binding.instance.$options.__scopeId, "");
  el.appendChild(span);
},

In the DOM, the element we will have the scope ID attached. Now we don’t need to use :deep() or /deep/ anymore for the directive-created element.

<span data-v-0fb92912=""></span>
Manslayer answered 30/7, 2023 at 9:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.