Change in HTML attribute of web component not reflected in Vue component

716 views Asked by At

I'm facing the below problem.

I have a pure web component:

<my-web-comp options='["op1", "op2"]' active-option="op2"></my-web-comp>

This renders as two tabs with the second one selected by default. When you click on the other, the active-option HTML attribute changes to op1 and you can actually see that the property is changing in the DOM if you open the DevTools.

However, I cannot detect the change in the Vue component where I am using the web component. I have:

<template>
    <div>
       <my-web-comp :options="options" :active-option="activeOption"></my-web-comp> 
    </div>
</template>

<script>
   export default {
  name: 'MyVueComponent',
  data() {
    return {
      options: '["op1", "op2"]',
      activeOption: "op2"
    }
  },
  computed: {
    testVar() {
      console.log("activeOption", this.activeOption) <--------- THIS LINE
    },
  }
}
</script>

The marked line only gets fired on the first load of the Vue component (printing "op2"). After that, testVar never gets modified again, doesn't mind if I click on the other tab and I don't see nothing in the console.

What can I be missing? I think it can be something related with Vue reactivity system, but can't wonder what.

1

There are 1 answers

0
Krzysztof Kaczyński On

This happens because your web-component mutates copy not a reference of this variable (copy created by your web component is also not reactive). There are two ways to change this:

  • You can modify your web component to use getters and setters to change value of this variable
  • You can use MutationObserver. To detect changes in your web-component. This approach will not require changes in this web-component

If you choose approach with MutationObserver then create this observer in vue mounted life-cycle-hook