代码之家  ›  专栏  ›  技术社区  ›  ajthinking

Vue数据属性不响应

  •  0
  • ajthinking  · 技术社区  · 6 年前

    考虑到下面的代码,我不能 active 数据属性是被动的。在本例中,我只想在图像的鼠标上方显示div。

    <template>
        <div>
            <img @mouseover="showInfo" class="cursor-pointer w-full" :src="project.images[0].url" width="100%">
            <div v-show="active" class="bg-red h-12">
                Info about the image
            </div>
        </div>    
    </template>
    
    <script>
        export default {
            props: ['project'],
            data: function () {
                return {
                    active: false
                }
            },
            methods: {
                showInfo: () => {
                    this.active = !this.active;
                }
            }
        }
    </script>
    

    忙碌的

    4 回复  |  直到 6 年前
        1
  •  10
  •   Fab    6 年前

    不要使用箭头函数来定义方法, this 这是行不通的。

    替换

            showInfo: () => {
                this.active = !this.active;
            }
    

            showInfo() {
                this.active = !this.active;
            }
    
        2
  •  1
  •   Satyam Pathak    6 年前

    如果您只需更改 HTML 你不需要一个单独的方法。

    @mouseover="active = !active"
    

    看起来是这样的,,

    <div>
       <img @mouseover="active = !active" class="cursor-pointer w-full" :src="project.images[0].url" width="100%">
       <div v-show="active" class="bg-red h-12">
         Info about the image
       </div>
    </div> 
    
        3
  •  1
  •   Michael Mano    6 年前
    data() {
        return {
             active: false
         }
    },
    
    
    

    像上面那样更新您的数据。

    toggleInfo 因为它也可以在鼠标上隐藏它。

    toggleInfo() {
         this.active = !this.active;
     }