Vue refs Issue for children in v-for
HTML
<div id="app">
<h2>Todos:</h2>
<ol ref="orderedList">
<li v-for="(todo, i) in todos" :class="{active: !i}">
<label>
<input type="checkbox"
:ref="'input' + i"
v-on:change="toggle(todo)"
v-bind:checked="todo.done">
<del v-if="todo.done">
{{ todo.text }}
</del>
<span v-else>
{{ todo.text }}
</span>
</label>
</li>
</ol>
<test-component></test-component>
</div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
del {
color: rgba(0, 0, 0, 0.3);
}
Vue
Vue.component('test-component', {
template: `
<ol ref="orderedList">
<li v-for="(item, index) in list" :class="{active: !index}" ref="'item' + index">{{item.name}}</li>
</ol>
`,
data() {
return {
list: [
{name: 'John'},
{name: 'Alex'},
{name: 'Sam'},
{name: 'Shtefan'},
]
};
},
mounted() {
const ol = this.$refs.orderedList;
const active = ol.querySelector('.active');
console.log(ol, active);
}
});
new Vue({
el: "#app",
data: {
todos: [
{ text: "Learn JavaScript", done: false },
{ text: "Learn Vue", done: false },
{ text: "Play around in JSFiddle", done: true },
{ text: "Build something awesome", done: true }
]
},
methods: {
toggle: function(todo){
console.log(this.$refs)
todo.done = !todo.done
}
},
mounted() {
console.log(this.$refs);
console.log(this.$refs.orderedList);
const active = this.$refs.orderedList.querySelector('.active');
console.log(active);
}
})