【问题标题】:changing a button text dynamically in Vuejs在 Vuejs 中动态更改按钮文本
【发布时间】:2020-08-17 02:30:58
【问题描述】:

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

<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 }}。似乎是什么问题,我该如何解决?

【问题讨论】:

  • 你能分享一个演示或问题的小提琴吗?

标签: javascript html vue.js button watch


【解决方案1】:

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

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.";

      */
   }
}

【讨论】:

    猜你喜欢
    • 2017-01-30
    • 1970-01-01
    • 2014-04-15
    • 2021-11-25
    • 1970-01-01
    • 2011-06-29
    • 2021-04-19
    • 2016-01-13
    • 1970-01-01
    相关资源
    最近更新 更多