본문 바로가기

Dev.FrontEnd/Vue.js2

[Vue.js2] V-bind

V-bind란

 

 

✔️개념

  • 속성, 동적 클래스, 동적 스타일, HTML 속성 등 다양한 곳에 사용할 수 있다.
  • 객체 바인딩을 사용하면 여러 속성을 한 번에 바인딩할 수 있다.
  • v-bind는 vue에서 데이터와 DOM 속성을 연결하는 중요한 역할을 한다.

 

🔑Key-Point

v-bind를 통해 부모컴포넌트(app.vue)와 자식컴포넌트(test.vue)에 props를 동적으로 바인딩(연결) 할 수 있다.

한 예로 부모의 input에 v-model에 데이터가 변할 때마다, 자식컴포넌트의 데이터도 변경시킬 수 있다.

 

🛠️소스설명

*app.vue 

v-bind:속성명="데이터"를 하게 되면 자식컴포넌트에게 이 속성명과 데이터를 보내게 된다.

그럼 자식에서 이 속성명을 props의 속성으로 받아주면 된다.

부모에서 데이터를  props로 내릴 때 데이터를 객체로도 보낼 수 있고 스트링으로도 보낼 수 있고, 배열로도 보낼 수 있다.

 

*app.vue

<template>
  <div id="app">
    <!-- <img alt="Vue logo" src="./assets/logo.png"> -->
    <TestWorld ref="testWorld" msg="Welcome to Your Vue.js App"/>

    <!-- <input type="text" v-model="ksw4895"> -->
    <!-- <testKsw msg="hi"></testKsw> -->
    <testKsw msg="hi" v-bind:todo2="todo"></testKsw>
    <!-- <testKsw msg="hi" :my-message="ksw4895"></testKsw> -->




  </div>
</template>

<script>
import TestWorld from './components/Test-world.vue'
import testKsw from './components/test-ksw.vue'

export default {
  data() {
   return{
    ksw4895: '',

    todo: {
      text: 'Learn Vue',
      isComplete: false
    }
   }
  },
  name: 'App',
  components: {
    TestWorld,
    testKsw,
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

 

 

 

*test-ksw4895

<!-- test-ksw.vue -->
<template>
  <div>
    <p>text: {{ todo2.text }}</p>
    <p>isComplete: {{ todo2.isComplete }}</p>



  <div>
    <button v-bind="buttonProps">버튼</button>
  </div>

  </div>
</template>

<script>
export default {
  data() {
    return {
        buttonProps: {
        class: 'btn btn-primary',
        style: 'color: white; background-color: blue;',
        disabled: false
      }
    }
  },
  props: {
    todo2: Object
  }
};
</script>

 

 

🔄정리

v-bind는 HTML 속성에 데이터를 연결해주는 역할을 하며, 그 값이 동적으로 변할 때 관련된 속성도 자동으로 바뀌게 해준다. 예를 들어, 어떠한 이벤트로 인해 src에 대한 데이터가 변할 때, class, style., html 등이 변할 때 동적변화를 해준다.

 

'Dev.FrontEnd > Vue.js2' 카테고리의 다른 글

[vue.js 2] v-if vs v-show 차이점과 예제 비교  (0) 2025.01.13