Web Design Patterns

MVC

Model-View-Controller

  • M is Model, the data layer. Data related operations, including data add, delete, change and check
  • V is View, the View layer. User interface rendering logic, that is, the interface that the user can see
  • C is the Controller, the Controller. The bridge for communication between M and V, which handles events and then calls M and V to update data and views

MVP

Model-View-Presenter

  • M is Model, the data layer. Data related operations, including data add, delete, change and check
  • V is View, the View layer. User interface rendering logic, that is, the interface that the user can see
  • P is for Presenter, which is to respond to view instructions and perform relevant business processing at the same time. If necessary, Model will be called to obtain the underlying data, return the command results to the view, and drive the view rendering

MVVM

Model-View-ViewModel

  • M is Model, the data layer. Data related operations, including data add, delete, change and check
  • V is View, the View layer. User interface rendering logic, that is, the interface that the user can see
  • VMIt’s the ViewModel, the association between synchronization M and V, and the core of implementing synchronization association isDOM ListenersData BindingsTwo tools.DOMListenersUsed in listening VDOMAnd selectively transmitted to M;Data BindingsThe tool is used to listen for changes in M data and update it to V.

Vue life cycle

The process from creation to destruction of vUE instances

hook describe Usage scenarios
beforeCreateBefore creating When I first initialize the instance, I can’t get anything from the instance addloadingThe event
createdAfter creation Instance creation completed, data observation completed, properties and methods initialized,$dataA. However, the mount phase hasn’t even started yet,$elNo, not yet. The request data
beforeMountBefore the mount Called before mounting, relatedrenderThe function is called for the first time.$elInitialization is complete, but not yet mounted
mountedAfter a mount Mount and render completed, availabledomnode Operating componentsdomRequest and modify data
beforeUpdateBefore the update Data has changed before data update, butdomNot updated Access existing ones before updatingdom, such as manually removing added event listeners
updatedAfter the update To complete the virtualdomRerender and patch; componentdomUpdate completed, Execute dependentdomOperation,Pay attention to: Do not manipulate data in this function, it will get stuck in an endless loop
beforeDestroyBefore destruction The instance is still available until it is destroyed Clear up some resources, such as timers, event bindings, and so on
destroyedAfter the destruction of After the instance is destroyed, the component is gone and you can’t manipulate anything in it

BeforeMount The order of execution is the first parent and the second child. Mounted The order of execution is the first child and the second parent

Component communication

vuex eventBus

Parent-child component communication

Props, $emit, $parent, $children, provide Inject, $refs

Vue bidirectional binding principle

Data hijacking combines published-subscribe with set and get of Object.defineProperty() to publish messages to subscribers when data changes to trigger listening. Vue has a Watcher (subscriber) instance for each component instance, logs the data during component instance rendering as a dependency (that is, get of Object.defineProperty), informs Watcher when a dependency’s set fires, This causes its associated components to be re-rendered

V-if is different from V-show

V-if directly creates or destroys labels v-show Switching the display attribute of labels V-if has higher performance overhead than V-show. V-show is more suitable for labels that are frequently switched.

The role of key in V-for

Key is used to efficiently update the virtual DOM. Key is a node identifier. By default, V-for uses the in-place reuse strategy. When the list data is modified, it will judge whether a value is modified according to the key value. If the value is modified, it will re-render the item, otherwise the previous element will be reused.

V-if and V-for cannot be used together

V-for has a higher priority than V-if, and when used together, v-FOR performs V-IF every time, causing unnecessary computations and affecting performance, especially if it requires a small amount of rendering

Differences between computed, Watch and methods

The name of the describe Usage scenarios
computedCalculate attribute Support caching, only when the dependent data changes, will be recalculated; Asynchronous operations are not supported. Low overhead When a property needs to depend on more than onedataAttribute in
watchListen to attribute Caching is not supported. Whenever data changes, listener functions are executed. Asynchronous operations are supported. Spending big When asynchronous or expensive operations need to be performed when data changes
methodsmethods The function call, which does not support caching, is re-executed whenever the page is re-rendered Encapsulate toolclass functions, process business logic, etc

$nextTick

Accept a callback function and defer execution until the next DOM update loop

keep-alive

Built-in abstraction components. When a dynamic component is wrapped, inactive component instances are cached. Instead of destroying them. It is primarily used to preserve component state (in memory) and avoid re-rendering. Include – a string or regular expression. Only components with matching names are cached. Exclude – a string or regular expression. Any component with a matching name will not be cached. Max – Numbers. Maximum number of component instances can be cached.

Vuex

Vuex is a state management mode developed specifically for vue.js applications

The core describe Component class usage Auxiliary function
state Data source, status $store.state mapState
getters Calculate attribute $store.getters mapGetters
mutations The only way to change the state $store.commit mapMutations
actions submitmutationSupport asynchrony store.dispatch mapActions
modules Submodule, namespace:namespaced Interview with Lu Jin (name/) createNamespacedHelpers

Vue-router Navigation hook

Global hooks

  • beforeEach((to, from, next) => { })Mount to the entry route and execute before the entry route
  • afterEach((to, from) => { })Mount to the entry route and execute after the entry route

Route exclusive hooks

  • beforeEnter(to, from, next) { }Call before entering

A hook within a component

  • beforeRouteEnter(to, from, next) { }Call before entering
  • beforeRouteLeave (to, from, next) { }Call after entering
  • beforeRouteUpdate(to, from, next) { }Called when the current route changes, but the component is being reused, for example, dynamic routing

$route = $router

  • routerIs a global routing object,VueRouter, including route jump methods, hook functions, etc
  • routeIs a local routing information object containingpath,params,query,nameAnd other routing information parameters

Vue – the router to participate

  • paramsCan only usename, cannot be usedpath, the parameters will not be displayed on the path, and the browser forced refresh parameters will be cleared
  • queryParameters are displayed on the path and browser forced refresh is not cleared

Vue – the router mode

  • hashThe principle ishashchageEvents,#Symbols, which are not included in HTTP requests to guide browser actions, do not reload the page
  • historyTakes advantage of new additions to the HTML5 History InterfacepushStatereplaceStateMethods. Background configuration support is required. If the server does not have a responding resource, a 404 will be returned

Vue-common CLI configuration options

pages

Page configuration. You can apply the configuration on multiple pages. The default value is single page

  • entry: Page entry
  • template: Template source
  • filename: Output file

configureWebpack

Take a function or an object and merge it into the final WebPack configuration

// add 'babel-polyfill' to the page
configureWebpack: (config) = > {
    config.entry[page].unshift('babel-polyfill')},Copy the code

chainWebpack

Accept a function, more fine-grained control of its internal configuration, support chain operations

css

Some style specific configurations

  • loaderOptions: Passes options to the CSS-related loader. Such as the global SASS style file
    loaderOptions: {
      sass: {
        data: '@import "@/assets/scss/globle.scss"; '}}Copy the code

devServer

All webpack-dev-server options are supported

  • hot: hot update
  • portPort:
  • open: Automatically opens the browser
  • proxyRequest API proxy, cross domain

Vue3.0 new features

  1. setup: Composite API. In addition to thebeforeCreate,createdHook, usingsetupInstead.setupExecute before creating the component, oncepropsIs parsed and acts as a compositionAPIThe entry point of.
    • ref: reactive variable
    • onMounted: Lifecycle hooks
    • computed: Compute attributes
  2. Fragment: A component supports multiple root nodes
  3. Teleport: teleport, which places DOM elements in the specified container
  4. createApp: global API, callcreateAppReturn a root instance
  5. V-model: Supports multiple values