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

Rak*_*van 1 vue.js vue-component bootstrap-vue

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

所需输出的示例图像 我尝试在值发生变化时watchers进行更新。但是,使用此代码,按钮组的宽度似乎与上一个问题的宽度而不是当前问题的宽度匹配。我还尝试了其他属性,例如, , 。我只是无法让它正常工作。有没有更简单的方法来匹配两个元素的宽度?buttonWidthquestionupdatedmountedcreated

<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>
Run Code Online (Sandbox Code Playgroud)

在我的脚本下我有:

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;
    },
  },
};
Run Code Online (Sandbox Code Playgroud)

ski*_*tle 5

要让它与 a 一起工作,watch您需要 a $nextTick,否则组件将不会重新渲染,您仍然会测量旧的宽度:

watch: {
  question() {
    this.$nextTick(() => {
      this.buttonWidth = `width: ${this.$refs.quest.clientWidth}px;`;
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

也应该可以使用mountedupdated钩子而不是 来使其工作watch$nextTick如果你这样做的话,你就不应该需要。您提到您已经在问题中尝试过,但没有看到您尝试过的代码,很难知道为什么这对您不起作用。

另外,还不清楚为什么你有一个名为 的计算属性getWidth。为什么不buttonWidth直接使用呢?