본문 바로가기
Programming/Vue

[Vue] Vue의 Attribute Binding

by 혀코 2022. 8. 31.

 

안녕하세요. 혀코입니다.

 

이번 시간에는 Vue의 Attribute Binding에 대해서 알아보겠습니다.

 

v-bind

속성값으로 Vue의 데이터 값을 넣어줄 때는 이중괄호를 사용할 수 없습니다. 따라서 이때에는 v-bind directive를 사용합니다.

 

<template>
  <h1 v-bind:class="className" @click="change">{{msg}}</h1>
</template>

<script>
export default {
  data() {
    return {
      className: 'txt-red',
      msg: 'Hello World'
    }
  },
  methods: {
  	change() {
      this.className = 'txt-green'
    }
  }
}
</script>

<style scoped>
.txt-red {
  color: red
}

.txt-green {
  color: green
}
</style>

 

앱이 처음 실행될때 텍스트가 빨간색이였다가 클릭하면 녹색으로 변경하도록 코드를 짜보았습니다.

 

여기서 v-bind는 가장 흔하게 사용되는 directive로 다음과 같이 :로 축약해서 사용할 수 있습니다.

 

<template>
  <h1 :class="className" @click="change">{{msg}}</h1>
</template>

<script>
export default {
  data() {
    return {
      className: 'txt-red',
      msg: 'Hello World'
    }
  },
  methods: {
  	change() {
      this.className = 'txt-green'
    }
  }
}
</script>

<style scoped>
.txt-red {
  color: red
}

.txt-green {
  color: green
}
</style>

 

class 속성값을 동적으로 추가하려면 다음과 같이 중괄호 [ ] 으로 작성해 줍니다.

 

<template>
  <h1 :[attr]="className" @click="change">{{msg}}</h1>
</template>

<script>
export default {
  data() {
    return {
      className: 'txt-red',
      msg: 'Hello World',
      attr: 'class'
    }
  },
  methods: {
  	change() {
      this.className = 'txt-green'
    }
  }
}
</script>

<style scoped>
.txt-red {
  color: red
}

.txt-green {
  color: green
}
</style>

 

이렇게 하면, 여러 가지의 속성을 다이나믹하게 동적으로 추가할 수 있는 장점이 있습니다.

 

또한 지금까지 사용했던 @ 기호는 v-on directive의 약어로 이벤트 속성을 받습니다.

 

이벤트 속성도 다이나믹하게 동적으로 추가시 다음과 같이 코드를 작성할 수 있습니다.

 

<template>
  <h1 :[attr]="className" @[event]="change">{{ msg }}</h1>
</template>

<script>
export default {
  data() {
    return {
      className: 'txt-red',
      msg: 'Hello World',
      attr: 'class',
      event: 'click',
    }
  },
  methods: {
  	change() {
      this.className = 'txt-green'
    }
  }
}
</script>

<style scoped>
.txt-red {
  color: red
}

.txt-green {
  color: green
}
</style>

 

 

 

이렇게 Vue의 Attribute Binding에 대해서 알아봤습니다.

 

해당 정보가 유용하셨다면, 공감과 구독 부탁 드립니다.

 

감사합니다. :)

댓글