在vue中获取dom元素

2023-05-16

转发请备注原文链接地址:https://www.niwoxuexi.com/blog/web/article/307.html

在vue中经常会通过js操作dom对象,可以通过给标签添加ref属性实现,

下面通过操作dom对象实现一个点击按钮改变屏幕背景的demo,效果如下



下面是代码:

<template>
  <div class="box" ref="boxHook">
    <div class="change-button" @click="changeBackground">Click me change backgroundColor </div>
  </div>
</template>

<script type='text/ecmascript-6'>
  export default{
    methods: {
      changeBackground() {
        var R = Math.floor(Math.random() * 255)
        var G = Math.floor(Math.random() * 255)
        var B = Math.floor(Math.random() * 255)
        var color = 'rgb(' + R + ',' + G + ',' + B + ')'

        this.$refs.boxHook.style.background = color
      }
    }
  }
</script>

<style lang='stylus' rel='stylesheet/stylus'>
  .box
    width 100%
    height 100%
    background #ffffff
    padding-top 200px
    .change-button
      width 320px
      height 60px
      line-height 60px
      text-align center
      margin 0 auto
      color #ffffff
      font-size 18px
      background green

</style>




本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在vue中获取dom元素 的相关文章