본문 바로가기

WEB Developer/Vue JS

v-if, v-for, list 예시

Conditional Centent Lists v-for Variations Keys
v-if (and v-show) allows you to render content only if a certain condition is met v-for can be used to render multiple elements dynamically You can extract values, values and indexes or values, keys and indexes Vue re-uses DOM elements to optimize performance à This can lead to bugs if elements contain state
v-if can be combined with v-else and v-else-if (only on direct sibling elements!) v-for can be used with arrays, objects and ranges (numbers). If you need v-for and v-if, DON’T use them on the same element, Use a wrapper with v-if instead. Bind the key attribute to a unique value to help Vue identify elements that belong to list content

 

 
 <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vue Basics</title>
    <link
      rel="stylesheet"
    />
    <link rel="stylesheet" href="styles.css" />
    <script src="https://unpkg.com/vue@3.4.9/dist/vue.global.js" defer></script>
    <script src="app.js" defer></script>
  </head>
  <body>
    <header>
      <h1>Vue Lists and Conditional Content</h1>
    </header>
    <section id="assignment">
      <h2>Assignment</h2>
      <!-- 1) Add code to manage a list of tasks in a Vue app -->
      <!-- When clicking "Add Task" a new task with the entered text should be added -->
      <input type="text" v-model="enteredTask">
      <button @click="addGoal">Add Task</button>
      <ul v-if="paragraphVisible">
        <!-- 2) Output the list of tasks here -->
        <li v-for="taskItem in listTasks" :key="taskItem">
          <p>{{ taskItem }}</p>
        </li>
      </ul>
      <!-- 3) When the below button is pressed, the list should be shown or hidden -->
      <!-- BONUS: Also update the button caption -->
      <p></p>
      <!-- <button @click="toggleParagraphVisibility">{{ paragraphVisible ? 'Hide' : 'Show' }} </button> -->
      <button @click="toggleParagraphVisibility">{{ changeButton }} </button>
    </section>
  </body>
</html>

 

 
const app = Vue.createApp({
    data() {
        return {
            listTasks: [],
            enteredTask: '',
            paragraphVisible: true,
            buttonName: "Hide"
        }
    },
    computed: {
        changeButton() {
            return this.paragraphVisible ? 'Hide List' : 'Show List';
        }
    },
    methods: {
        addGoal() {
            this.listTasks.push(this.enteredTask);
        },
        toggleParagraphVisibility() {
            this.paragraphVisible = !this.paragraphVisible
        }

    }
});

app.mount('#assignment');