在vue中获取dom元素

作者: web 发布时间: 2017-09-21 浏览: 5718 次 编辑

在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>
标签: vue dom javascript ref