VueJs:如何根据另一个元素更新元素的宽度?

问题描述 投票:0回答:1

我正在构建Trivia应用程序,并且我有一个<h1>元素,该元素每10秒更改一次。我想使单选按钮组组件的宽度(b-form-groupBootstrap-Vue component)与<h1>元素的宽度匹配。像这样:

example image of the desired output每当watchers的值更改时,我尝试使用buttonWidth更新question。但是,使用此代码,按钮组的宽度似乎与上一个问题的宽度匹配,而不是当前问题的宽度。我还尝试了其他属性,例如updatedmountedcreated。我只是无法使其正常工作。有没有更简单的方法来匹配两个元素的宽度?

<template>
  <div>
    <div id="question">
       <h1 ref="quest">{{ question }}</h1>
    </div>

    <b-form-group>
      <b-form-radio-group :style=getWidth
        ref="opts"
        :options="options"
        buttons
        stacked
        button-variant="outline-primary"
        size="lg"
        name="radio-btn-stacked"
      ></b-form-radio-group>
    </b-form-group>
  </div>
</template>

根据我的脚本,我有:

export default {
  props: ['question', 'options'],
  data() {
    return {
      buttonWidth: '0 px',
    };
  },
  methods: {
  },
  watch: {
    question() {
      // console.log('Updating button width to ', this.$refs.quest.clientWidth);
      this.buttonWidth = `width: ${this.$refs.quest.clientWidth}px;`;
    },
    // immediate: true,
  },
  computed: {
    getWidth() {
      return this.buttonWidth;
    },
  },
};
vue.js vue-component bootstrap-vue
1个回答
0
投票

样式绑定应类似于:style="{width:getWidth}"

<template>
  <div>
    <div id="question">
       <h1 ref="quest">{{ question }}</h1>
    </div>

    <b-form-group>
      <b-form-radio-group :style="{width:getWidth}"
        ref="opts"
        :options="options"
        buttons
        stacked
        button-variant="outline-primary"
        size="lg"
        name="radio-btn-stacked"
      ></b-form-radio-group>
    </b-form-group>
  </div>
</template>

在watcher属性中,仅尝试定义宽度值,而不添加属性名称this.buttonWidth = $ {this。$ refs.quest.clientWidth} px``:

export default {
  props: ['question', 'options'],
  data() {
    return {
      buttonWidth: '0 px',
    };
  },
  methods: {
  },
  watch: {
    question() {
      // console.log('Updating button width to ', this.$refs.quest.clientWidth);
      this.buttonWidth = `${this.$refs.quest.clientWidth}px`
    },
    // immediate: true,
  },
  computed: {
    getWidth() {
      return this.buttonWidth;
    },
  },
};
© www.soinside.com 2019 - 2024. All rights reserved.