Vue Js Select dynamic (multiple) elements:In Vue.js, refs provide a way to access and manipulate the underlying DOM elements directly from a component. When selecting multiple dynamic elements using refs, you can create an array to hold the refs and then use a loop to dynamically generate elements while assigning refs to them. This allows for a more flexible and dynamic approach to managing elements in a component. By using refs, you can also access component instances or child components programmatically, making it easier to build complex and dynamic user interfaces
How can I dynamically select multiple elements in Vue js?
This Vue.js code renders a list of items using v-for
directive and assigns a unique key to each item using :key
binding. It also adds a button that, when clicked, calls the changeColor()
method, which changes the color of all elements in the list to red.
To achieve this, the changeColor()
method first obtains an array of all the elements in the list using the $refs
object. $refs
is a special object in Vue.js that provides access to all the DOM elements with ref
attributes in the component’s template. In this case, each item in the list has a ref
attribute set to "itemRefs"
, so this.$refs.itemRefs
returns an array of all the elements with that ref
.
The method then loops through each element in the array and sets its style.color
property to 'red'
, which changes the color of the text to red
Vue Js Select dynamic (multiple) elements Example
<div id="app">
<div v-for="(item, index) in items" :key="index" ref="itemRefs">{{item}}</div>
<button @click="changeColor()">Change Color</button>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
items: ['Apple', 'Orange', 'Banana'],
};
},
methods: {
changeColor() {
const itemRefs = this.$refs.itemRefs; // Get array of refs
for (let i = 0; i < itemRefs.length; i++) {
itemRefs[i].style.color = 'red'; // Change color of each element
}
},
}
});
</script>