在 Vuejs 中动态更改按钮文本

changing a button text dynamically in Vuejs

如果值为 true/false,我想更改按钮的文本。 这是我的代码:

<button
  class="btn btn-primary table-button"
  type="button"
  data-toggle="collapse"
  :data-target="`#collapse${row.num}`"
  aria-expanded="false"
  aria-controls="collapseExample"
  @click="expanded = !expanded"
  ref="tableButtonText">
     {{ tableButtonText }}
</button>

data(){
  return{
    expanded:"",
    tableButtonText:""
  }
},
watch: {
    expanded() {
      if (this.expanded) {
        this.tableButtonText = "Hide details";
      } else if (!this.expanded) {
        this.tableButtonText = "View details";
      }
    }
  },

它确实改变了 expandedtableButtonText 的值,但屏幕根本不显示按钮。问题似乎是 html 没有呈现 {{ tableButtonText }}。似乎是什么问题,我该如何解决?

expanded 字段在初始化期间应标记为布尔值(默认为 false),而不是空字符串。此外,您缺少 template 字段来包装您的 HTML.

template:
`
<button
  class="btn btn-primary table-button"
  type="button"
  data-toggle="collapse"
  :data-target="`#collapse${row.num}`"
  aria-expanded="false"
  aria-controls="collapseExample"
  @click="toggleView">
     {{ text }}
</button>
`,
data() {
   return {
      expanded: false,
      text: "View details."
   }
},
methods: {
   toggleView() {
      this.expanded = !this.expanded;

      if (this.expanded) {
         this.text = "Hide details.";
      } else {
         this.text = "View details.";
      }

      /*

      OR ...

      this.text = (this.expanded)
         ? "Hide details."
         : "View details.";

      */
   }
}