refs i Vue er måske en lille del af VueJS, men er et meget brugbart element.
I eksemplet herunder er der lavet en lille notes-applikation med Vue via CDN. Læg mærke til, at i HTML er der sat ref-attributes, inputTitle
og inputNote
. I app.js refereres der til DOM-elementerne med this.$refs.inputTitle
<!--HTML-->
<div id="app">
<div class="wrapper">
<h1>My Notes</h1>
<div class="box">
<p>Indtast note</p>
<label for="title">Titel</label>
<input type="text" id="title" ref="inputTitle">
<label for="note">Note</label>
<textarea name="" id="note" cols="30" rows="10" ref="inputNote"></textarea>
<button class="btn" id="sendNote" @click="createNote">Indsæt note</button>
</div><!--/.box-->
<div class="box" v-for="(note, index) in notes">
<h2>{{ note.title }}</h2>
<time>{{ note.noteTime }}</time>
<p>{{ note.noteContent }}</p>
<button class="btn" @click="deleteNote(index)">Slet note</button>
</div>
</div><!--/.wrapper-->
</div>
<script src="app.js"></script>
/*app.js*/
const app = Vue.createApp({
data() {
return {
notes: [
]
}
},
methods: {
createNote () {
let d = new Date();
this.notes.push({
title: this.$refs.inputTitle.value,
noteContent: this.$refs.inputNote.value,
noteTime: d.getTime()
})
},
deleteNote (arg) {
this.notes.splice(arg, 1);
}
}
})
app.mount("#app");
- Introduktion til VueJS
- Vue – Events
- Vue – Methods
- Vue – Directives
- Vue – Attribute binding
- Vue – Computed properties
- Vue – refs
Læs mere om Vue