tbowden
tbowden

Reputation: 1058

Vue - Setting the width of a component dynamically

I can't figure out how to dynamically set the width of a component.

I am using the component 'vue-burger-menu' -> https://github.com/mbj36/vue-burger-menu.

To set the width one needs to set the prop width to a number. As per the example below:

<Slide
      ref="slideToggle"
      disable-esc
      class="slideToggle"
      width="470"
      right
      :burger-icon="false"
      :cross-icon="false"
      disable-outside-click
    >

It then sets a helper class - bm-menu width to the width. I have spent quite a while trying to figure out how to either set the prop's attribute dynamically or dynamically update the style.

For example I tried setting: this.$refs.slideToggle.$attrs.width = 1000 to no avail.

I can't bind a style to the bm-menu class as it's not visible.

How do I set the width so on the click of a button it changes (as per the button example below)?

Thanks for your help!

setDrawWidth() {
        this.lineDrawWidth = "200px";
    }

Upvotes: 0

Views: 7098

Answers (2)

Alireza HI
Alireza HI

Reputation: 1933

You just need binding which uses : before props:

<Slide
      ref="slideToggle"
      disable-esc
      class="slideToggle"
      :width="width"
      right
      :burger-icon="false"
      :cross-icon="false"
      disable-outside-click
>

And then in your data in js part:

export default {
     data:() => ({   width: '470'  }),
}

Now you just need to change width variable. For example:

export default {
     data:() => ({   width: '470'  }),
     methods:{
          changeWidth(){
               this.width = '1000';
          }
     }
}

You can read more about binding variables from the doc: Vue Props

Upvotes: 4

BeHappy
BeHappy

Reputation: 3978

Listen on window width event:

data: () => ({
  width: 470
})
created() {
  window.addEventListener("resize", this.changeWidth);
},
destroyed() {
  window.removeEventListener("resize", this.changeWidth);
},
methods: {
  changeWidth(e) {
    const screenWidth = window.innerWidth;
    this.width = screenWidth
  }
}

and set width in Slide component:

<Slide
      ref="slideToggle"
      disable-esc
      class="slideToggle"
      :width="width"
      right
      :burger-icon="false"
      :cross-icon="false"
      disable-outside-click
    >

Upvotes: 0

Related Questions