MOCKSTACKS
EN
Questions And Answers

More Tutorials









VueJs Pages Navigation with keep-alive

Pages Navigation with keep-alive


Sometimes you want to keep the switched-out components in memory, to make that happen, you should use
<keep-alive>
element:

Javascript:


new Vue({
 el: '#app',
 data: {
 currentPage: 'home',
 },
 methods: {
 switchTo: function(page) {
 this.currentPage = page;
 }
 },
 components: {
 home: {
 template: `<div>
 <h2>Home</h2>
 <p>{{ homeData }}</p>
 </div>`,
 data: function() {
 return {
 homeData: 'My about data'
 }
 }
 },
 about: {
 template: `<div>
 <h2>About</h2>
 <p>{{ aboutData }}</p>
 </div>`,
 data: function() {
 return {
 aboutData: 'My about data'
 }
 }
 },
 contact: {
 template: `<div>
 <h2>Contact</h2>
 <form method="POST" @submit.prevent>
 <label>Your Name:</label>
 <input type="text" v-model="contactData.name" >
 <label>You message: </label>
 <textarea v-model="contactData.message"></textarea>
 <button type="submit">Send</button>
 </form>
 </div>`,
 data: function() {
 return {
 contactData: { name:'', message:'' }
 }}
 }
})

HTML:


<div id="app">
 <div class="navigation">
 <ul>
 <li><a href="#home" @click="switchTo('home')">Home</a></li>
 <li><a href="#about" @click="switchTo('about')">About</a></li>
 <li><a href="#contact" @click="switchTo('contact')">Contact</a></li>
 </ul>
 </div>
 <div class="pages">
 <keep-alive>
 <component :is="currentPage"></component>
 </keep-alive>
 </div>
</div>

CSS:


.navigation {
 margin: 10px 0;
}
.navigation ul {
 margin: 0;
 padding: 0;
}
.navigation ul li {
 display: inline-block;
 margin-right: 20px;
}
input, label, button {
 display: block
}
input, textarea {
 margin-bottom: 10px;
}


Conclusion

In this page (written and validated by ) you learned about VueJs Pages Navigation with keep-alive . What's Next? If you are interested in completing VueJs tutorial, your next topic will be learning about: VueJs Event Bus.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.