Skip to content

Kapitel 7: Vue 3 Grundlagen (Teil 1)

📗 Lernziel: Vue Instanz, Template-Syntax und Datenbindung verstehen!


7.1 Vue Instanz und Template-Syntax

Eine Vue App erstellen:

javascript
// src/main.js
import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')

main.js erklärt:

  1. createApp(App) - Erstellt eine Vue Anwendung
  2. .mount('#app') - Bindet die App an das DOM-Element

index.html:

html
<body>
  <div id="app"></div>
  <script type="module" src="/src/main.js"></script>
</body>

7.2 Template-Syntax: Interpolation

(Mustache-Syntax):

  • Bindet Daten in das Template
  • Zeigt Variablenwerte an
  • Kann JavaScript-Ausdrücke enthalten

Beispiel:

vue
<script setup>
import { ref } from 'vue'

const message = ref('Hello Vue!')
const number = ref(10)
</script>

<template>
  <!-- Einfache Variable -->
  <p>{{ message }}</p>
  
  <!-- JavaScript-Ausdrücke -->
  <p>{{ number + 5 }}</p>
  <p>{{ message.toUpperCase() }}</p>
  <p>{{ number > 5 ? 'Groß' : 'Klein' }}</p>
</template>

Wichtig:

  • ✅ Einfache Ausdrücke erlaubt
  • ❌ Keine Anweisungen (if, for)
  • ❌ Keine Funktionsdeklarationen

7.3 Datenbindung: ref() und reactive()

ref() - Für primitive Werte:

vue
<script setup>
import { ref } from 'vue'

// Primitive Werte
const count = ref(0)
const message = ref('Hello')
const isVisible = ref(true)

// Zugriff im Script (`.value` nutzen!)
const increment = () => {
  count.value++
  console.log(count.value)
}
</script>

<template>
  <!-- Template (kein .value!) -->
  <p>{{ count }}</p>
  <p>{{ message }}</p>
  <p>{{ isVisible }}</p>
</template>

reactive() - Für Objekte:

vue
<script setup>
import { reactive } from 'vue'

const state = reactive({
  count: 0,
  message: 'Hello',
  user: {
    name: 'Max',
    age: 25
  }
})

// Zugriff ohne .value
const increment = () => {
  state.count++
  state.user.age++
}
</script>

<template>
  <p>{{ state.count }}</p>
  <p>{{ state.user.name }}</p>
</template>

Wann ref vs reactive?

  • ref: Für primitive Werte (number, string, boolean)
  • reactive: Für Objekte/Arrays

✅ Zusammenfassung

In diesem Kapitel hast du gelernt:

  • ✅ Vue Instanz erstellen (createApp)
  • ✅ Template-Syntax ()
  • ✅ Datenbindung mit ref() und reactive()

🎯 Nächster Schritt: In Kapitel 8 lernst du Vue Directive!


← Zurück zu Kapitel 6: Projekt erstellenWeiter zu Kapitel 8: Vue Directive →

Frei für alle Anfänger