days since this article was written, please be aware of its timeliness
Introduction
The Vue learning summary is basically complete. Next, I’ll supplement some fragmented knowledge. Today, let’s discuss three implementation methods of Vue Router.
View the complete project code (This project contains other Vue test code such as Vue Plugin, etc.)
Via the render Function
The basic idea is that the render function renders component content based on the address bar path. By using HTML5’s history.pushState and listening to popstate events, it can achieve routing functions like direct address access, browser back/forward navigation, and link-click jumps.
Advantages:
- Non-existent addresses can be redirected to a 404.vue page.
Disadvantages:
- Browsers that don’t support the HTML5 history.pushState API cannot be polyfilled.
- The rendering of the render function cannot be cached.
Note: If using transition animations, the root element exists in default.vue. Pay attention to the difference in the code compared to the method below.
View specific code
Via the is Attribute of the component
The principle is the same as above, but the render function is replaced with a component.
The component has an is attribute, which specifies which template the component should load. This attribute can be dynamically set based on the address bar path through custom logic.
Advantages:
- The component can be cached using the keep-alive attribute, making it more efficient than the render function above.
Disadvantages:
- Browsers that don’t support the HTML5 history.pushState API cannot be polyfilled.
- Non-existent route addresses (e.g., 404) cannot be rendered (hence, this Demo doesn’t include a 404.vue like the previous method).
Note: If using transition animations, the root element exists in tpl.html. Pay attention to the difference in the code compared to the method above.
View specific code
Via the VueRouter Plugin
VueRouter is an official plugin that perfectly fulfills all requirements.
Advantages:
- All necessary features are included.
Disadvantages:
- To polyfill pushState, a # is appended to the path to enable routing functionality, which is not true routing but merely a hash value change.
View specific code
I often wish that when facing some key decisions in life, someone could tell me the best course of action so that I would not waste my precious time. Putting myself in others' shoes, I therefore write blogs often, hoping to record in this tiny corner of the vast Internet the once-in-a-lifetime experiences that matter to me, and to help those who seek help.