【问题标题】:VueJS Update Dom After Calling Simple Method Not Working调用简单方法后VueJS更新Dom不起作用
【发布时间】:2018-03-18 02:21:33
【问题描述】:

我想在单击按钮时动态更改按钮的颜色。因此,我添加了一个自定义类“活动”,仅当属性 isActive 设置为 true 时才应分配该类。单击时,我想调用一个将属性更改为 true 的方法,然后更新 dom 以添加自定义类。任何帮助表示赞赏;)

<div v-for="(funktion, index) in funktions">
          <button class="btn btn-default wordcloud" 
                  :class="{ 'custom-active': funktion.isActive }" 
                  @click="activate(index)">{{funktion.name}}</button>
</div>

方法正确更新数据但dom不更新

export default {

  data() {
    return {
      funktions: [
          {
            name: "finanzen",
            isActive: false
          },
          {
            name: "management",
            isActive: false
          },
          {
            name: "testfield",
            isActive: false
           },
       ],
    };
  },
  methods: {
    activate(index){
        this.funktions[index].isActive = true;
    },
};

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component


    【解决方案1】:

    您没有将索引传递给activate 回调。将其更改为:

    @click="activate(index)">{{funktion.name}}</button>
    

    如果您在控制台中查看,您会看到一个异常,因为您正在尝试访问具有非数字的数组项。

    new Vue({
      el: '#app',
      data() {
        return {
          funktions: [
              {
                name: "finanzen",
                isActive: false
              },
              {
                name: "management",
                isActive: false
              },
              {
                name: "testfield",
                isActive: false
               },
           ],
        };
      },
      methods: {
        activate(index){
            this.funktions[index].isActive = true;
        },
    	},
    })
    .custom-active {
      background-color: red;
    }
    <script src="https://unpkg.com/vue"></script>
    
    <div id="app">
      <div v-for="(funktion, index) in funktions">
        <button class="btn btn-default wordcloud" 
          :class="{ 'custom-active': funktion.isActive }" 
          @click="activate(index)">{{funktion.name}}</button>
      </div>
    </div>

    【讨论】:

    • 对不起,我已经这样做了,这是问题的错误,我会编辑。还有其他想法吗?
    • 那么我不确定你在问什么,因为你的代码已经在点击时添加了活动类?
    • 点击后数据会正确更改,但 Dom 不会更新。如果我手动将“isActive”更改为 true,则在重新加载时会正确分配类
    • dom 对我来说更新得很好
    • 什么鬼?好吧,不能与之争论,那就不知道了
    猜你喜欢
    • 2017-12-31
    • 1970-01-01
    • 2018-02-09
    • 2014-06-20
    • 1970-01-01
    • 2013-09-11
    • 2011-12-02
    • 2017-03-19
    相关资源
    最近更新 更多