karol-f / vue-custom-element

Vue Custom Element - Web Components' Custom Elements for Vue.js
https://karol-f.github.io/vue-custom-element/
MIT License
1.97k stars 187 forks source link

Is there a way to access attributes (not defined as props) from the web-component using this.$attrs? #197

Closed jennale closed 4 years ago

jennale commented 4 years ago

Hi!

Is there a way of referencing attributes defined on a web-component (which are not defined as props) inside the vue component? This would ideally be done using this.$attrs, but I'm wondering if there's already another way.

For example:

<widget-vue prop1="1" prop2="string" class="someClass" some-attr="false"></widget-vue>

And the component definition:

Vue.customElement('widget-vue', {
  props: [
    'prop1',
    'prop2'
  ],
  mounted() {
     console.log(this.$props);   //Currently returns the props object correctly
     console.log(this.$attrs);     //Currently returns an empty object
  }
});

Ideally, console.log(this.$attrs); would print out an object containing class and someAttr. Currently it outputs an empty object.

Here's a codeSandbox as well: https://codesandbox.io/s/jovial-morning-41vru

jennale commented 4 years ago

Nevermind, I see that this might be a clone of #112.

Although, I wonder given that this.$slots and this.$props etc return info as expected, if we could expose some way of accessing this.$customElementAttrs too? Just to provide access programatically, but not necessarily passing it down as this.$attrs

karol-f commented 4 years ago

Hi, use e.g. vueInstanceCreatedCallback (this should refer to root DOM element) - https://github.com/karol-f/vue-custom-element#options or just this.$root.$el.parentNode.attributes. Regards.

tiago-freire commented 3 years ago

Hi, use e.g. vueInstanceCreatedCallback (this should refer to root DOM element) - https://github.com/karol-f/vue-custom-element#options or just this.$root.$el.parentNode.attributes. Regards.

@karol-f there are differences between this.$el and this.$root.$el?

karol-f commented 3 years ago

@tiago-freire didn't check it. You can easily try both versions