【问题标题】:Change style attribute of a generated div on click单击时更改生成的 div 的样式属性
【发布时间】:2019-06-24 00:36:20
【问题描述】:

我在搞乱 vue-cli 并且遇到了问题。

我有一排 24 个 div 像这样生成:

 <template>
   <div class="row">
     <div class="hour" v-on:click="colorize" v-for="n in 24"></div>
   </div>
 </template>

我正在尝试根据 VueX 商店中保存的值更改点击的 hour div 的背景颜色,但这不是重要的部分

这是我的方法:

methods: {
  colorize() {
    if(this.$store.state.picked === 1) {
      this.style.backgroundColor="rgb(103, 103, 103)";
    }
  }
}

商店有效,问题来自“this”属性,我假设我使用错误。

有什么建议吗? :)

【问题讨论】:

    标签: javascript vue.js vue-cli


    【解决方案1】:

    this 指的是 Vue 实例而不是点击的元素,所以你应该这样做:

     methods: {
       colorize(event) {
         if(this.$store.state.picked === 1) {
           event.target.style.backgroundColor="rgb(103, 103, 103)";
         }
       }
     }
    

    new Vue({
      el: '#app',
      data() {
        return {
          elements: [
          {content:'content 1',tooltip:'tool tip 1'},
          {content:'content 2',tooltip:'tool tip 2'},
          {content:'content 3',tooltip:'tool tip 3'},
          {content:'content 4',tooltip:'tool tip 4'},
          ]
        }
      }
    , methods: {
       colorize(event) {
     
           event.target.style.backgroundColor="rgb(103, 103, 103)";
         
       }
     }
    })
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    
    <div id="app" data-app>
    
     <div class="row">
         <div class="hour" v-on:click="colorize" v-for="n in elements">
         {{n.content}}
         </div>
       </div>
    </div>

    【讨论】:

    • 非常感谢,原来如此:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 2015-11-08
    • 2013-11-04
    • 2020-09-27
    • 2019-04-10
    • 2018-04-23
    相关资源
    最近更新 更多