Vue中常见的设计模式有哪些呢?
- 单例模式
const app = new Vue({
});
const store = new Vuex.Store({
state: {
count: 0
}
});
- 观察者模式
export default {
data() {
return {
message: 'Hello'
}
},
watch: {
message(newValue, oldValue) {
console.log('数据变化了', newValue, oldValue);
}
}
}
- 发布订阅模式
export default {
methods: {
handleClick() {
this.$emit('custom-event', data);
}
},
mounted() {
this.$on('custom-event', this.handleEvent);
}
}
<child-component @custom-event="handleEvent" />
- 工厂模式
Vue.component('button-counter', {
data() {
return {
count: 0
}
},
template: '<button @click="count++">点击了{{ count }}次</button>'
});
const ComponentFactory = {
createComponent(type) {
switch(type) {
case 'button':
return ButtonComponent;
case 'input':
return InputComponent;
default:
return null;
}
}
}
- 代理模式
const handler = {
get(target, key) {
track(target, key);
return target[key];
},
set(target, key, value) {
target[key] = value;
trigger(target, key);
return true;
}
};
const state = new Proxy({
count: 0
}, handler);