Implementing a feature to toggle between list and grid views in Vue.js involves managing the state of the view mode (list or grid) and updating the UI accordingly. You can achieve this by using Vue's reactivity system and conditional rendering. Here's a simple example of how you can implement it:
html<template>
<div>
<button @click="toggleViewMode">{{ viewMode === 'list' ? 'Grid View' : 'List View' }}</button>
<div v-if="viewMode === 'list'">
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
</div>
<div v-else>
<div class="grid-container">
<div v-for="item in items" :key="item.id" class="grid-item">{{ item.name }}</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
viewMode: 'list', // initial view mode
items: [ // sample data
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
// add more items as needed
]
};
},
methods: {
toggleViewMode() {
this.viewMode = this.viewMode === 'list' ? 'grid' : 'list';
}
}
};
</script>
<style>
/* Add your CSS styles for grid view here */
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
grid-gap: 10px;
}
.grid-item {
border: 1px solid #ccc;
padding: 10px;
}
</style>
In this example:
viewMode
data property, either a list or grid layout is rendered.toggleViewMode
method changes the value of viewMode
between 'list' and 'grid'.You can customize this example further to fit your specific needs, such as adjusting the CSS for the grid layout or adding additional functionality.