Vuex alternatives;
-
Disadvantages of Vuex 1, cause unnecessary volume; 2, cause complex management trouble;
-
alternative
-
Register a bus globally
//index.js
Vue.prototype.bus = new Vue();
Copy the code
Emit events via $emit
//App.vue
this.bus.$emit('change'.'I'm passing the argument')
Copy the code
Listen in Mounted in the component that needs to listen for the above events
//HelloWorld.vue
mounted(){
this.bus.$on('changeDep',(msg)=>{
this.msg = 'Triggered by app.vue clicking on an image'+msg; })},Copy the code
Principle: Using vUE’s own observer mode to monitor events;
Disadvantages: 1, every time to trigger events, monitoring events, trouble to manage; 2, Vue. Prototype. Bus = new Vue(); It’s not elegant;
- 2. Easy Store
Create a mystore.js
import vue from 'vue';
export const store = vue.observable({a:123});
exportconst mutations = { changeDep(msg){ store.a = msg; }}Copy the code
//HelloWorld.vue
computed:{
a() {returnstore.a; }}Copy the code
Packaging optimization
1. Reduce resolve and limit include; 2. DLL principle; 3, happypack;
-
Plug-ins To solve project problems Why do you need plug-ins? Provides your global custom operations. There are always special needs within a project, and plug-ins are there for us to solve those needs. It can be injected into the life cycle of each component and then do something automatically.
-
Requirement: The vuEX of the project is too large (for example, hundreds of data in vuex will be packaged into app.js at last), leading to the processing of the packaged result is too large: load vuex asynchronously by component split
directory
Plug-in to write
var obj = {
install:function(vue){
vue.mixin({
created:function() {if(this.$options.isVuex){
var name = this.$options.name; // Dynamic import is lazy loading and will not be packaged with app.js import('.. /store/modules/'+name).then((res)=>{
this.$store.registerModule(name,res.default);
});
}
}
})
}
}
module.exports = obj;
Copy the code
The contents of the module, such as store/modules/HelloWorld) content in js:
export default{
state:{
number1:1
}
}
Copy the code
After this dynamic introduction, you can retrieve the contents of the module when accessing HelloWorld.vue