The MVVM pattern

The bidirectional binding of the view to the model means that changes to the data result in changes to the page. Views are separated from models.

graph TD
view --> viewmodel --> model --> viewmodel --> view

At the beginning of the vue experience

Introduce it into HTML to use VUE related syntax.

<! Version, development environment, contains useful command-line warning -- > < script SRC = "https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js" > < / script > <! - production version, optimized the size and speed -- > < script SRC = "https://cdn.jsdelivr.net/npm/vue@2" > < / script >Copy the code

Instance and data binding

Var app = new Vue({el:'#dom') {} // Data binding, value is a JS object}) console.log(app.$el,app.data object key) // access modeCopy the code

Interpolation and expression

Double braces {{}} is a text interpolation method, can realize two-way data binding, you can use three yuan operation results, you can use pipe calculation results {{data | formatDate}} (), the result calculated by the function on the right

Tag attributes (directives and events)

  • V-html output HTML directly (XSS processing required)
  • The V-Pre skips compilation
  • V-bind dynamically updates attributes on HTML elements = syntactic sugar: HTML element attributes
    • Class =”{‘active’:isActive}”
    • Set methods that you can use to calculate properties to get values
    • Set array, :class=”[Activecss,errorcss]”
    • :style=” > < span style=” font-family: 宋 体
  • V-on binding event listener = syntax-sugar@js event
  • V-cloak is removed from the bound HTML element when the instance finishes compiling
  • A V-once element or component is rendered only once
  • The key attribute causes the element to be re-rendered
  • V-if/V-show show applies to frequently switching conditions, and if applies to scenarios that do not change frequently
  • Any method v-for uses to change the value of the original array causes the element to be re-rendered
  • @click Event syntax sugar passes the event to the method if it has an argument. The vue special variable $event is used to access native DOM events
  • V-model form elements bind data bidirectionally, with values that are the default values of the form; The default is to look for its value property, if not the value of text
  • V-model. lazy will only render when out of focus
  • V-model. trim Trim the leading and trailing Spaces of the string
  • :value Dynamic modification of the form value
<div id ="app"> <select v-model ="selected"> <option : value ="{ number : 123 }"> 123</option> </select> {{ selec; ted.number }} </div> <script> var app =new Vue ({ el :'#app', data : { selected :'' }) </script>Copy the code
  • @input handles the input field

Custom instruction

There are the following hook functions

  • Bind: called only once and can be used to initialize actions
  • Inserted: Called when the bound element is inserted into the parent node
  • Update: Called when the template to which the bound element belongs is updated
  • ComponentUpdate: Called when the template to which the bound element belongs has completed an update cycle
  • Unbind: Called only once, when an instruction is unbound from an element

Each hook function takes the following parameters

  • The element bound by the el directive
  • Binding (object. Take the following demo as an example)
    • Name Indicates the command name test
    • Value Specifies the value bound to message by the directive
    • OldValue performs the previous binding value
    • Expression The string form of the binding value message
    • Arg the parameter MSG passed to the instruction
  • Vnode Virtual node
  • A virtual node on an oldVnode
// test is the instruction name, message is the instruction value,  <div v-test:msg.a.b="message"></div> Vue.directive('test',{ bind:function(el,binding,vnode){} })Copy the code

The modifier

Its value can be a method or null.

<! <a @click.stop ="handle"></a> <! - submit event no longer reload - > < a @ submit. Prevent = "handle" > < / a > < a @ click. Stop. Prevent = "handle" > < / a > <! <div @click.capture ="handle "> <div @click.capture ="handle" > </div> <! <div @click.once ="handle ">... </div> <! <div @key.13 ="handle ">... </div> <! Configure specific buttons. @keyup.fl- > vue.config. keycodes. fl = 112;Copy the code

component

  1. The props types for components are: String, Number, Boolean, Object, Array, and Function. Support custom validator:(data)=>{return data>10}
<div id ="app" >< my-component maessage=" parent "></my-component> </div> <script> var child = {template:'<div> local </div>'} vue.component ('my-component',{props:['message'], / props:['message'], / props:['message'], / props:['message'], / props:['message'], / props:['message'], / props:['message'], / props:['message'] Template :'<div>test</div>',// template must be wrapped in an HTML element data:()=>{// The difference with the instance is that the component data must be a function, And return {... }})} var app = new Vue({el :'#app', components:{'my-component':child}) </script>Copy the code
  1. Component communication
Graph TD child 1 --> child 2 --> child 1 --> parent --> child 2
  • The child component fires (creates) the definition event on the custom component through $emit()
  • The parent listens for the child’s events via $on()
  • $refs retrieves the collection of child component indexes in the parent component
  • $parent gets the collection of parent components in a custom component
<my-component @increase="getTotal"></my-component> //my-component method definition template:'<button @click="handleClick">+l</button>' methods:{handleIncrease:()=>{// Trigger an external increase event inside a custom component $emit('increase',this.counter)}} var app = new Vue({methods:{getTotal:(total){}})Copy the code

A bus mode of communication between child and parent components. That is, father-child communication is connected through a bus

<component-a></component-a> var bus = new Vue(); template:'<button @click="handle"></button>', Bus.$emit('on-message',' message')}} Mounted ()=>{// Listen for on-message events bus.$on('on-message',(data)=>{}) }Copy the code

Calculate attribute

  • When dealing with complex logical processing, use computed properties. Separate the data from the logic and just return the results
  • Calculated properties can be used interchangeably across multiple VUE instances, and when data changes in one instance, the other instance changes
  • The calculation property is cacheable and is reevaluated only when data occurs. Instead of re-rendering, it will be computed
Var app =new Vue({computed:{processText:()=>{} // processText is returned as the value reflected on the page. Getter methods are used by default. FullName :{get ()=>{}, set (value)=>{} //app.fullName will call this method}}}) console.log(processText)Copy the code

The life cycle

Var app = new Vue({created ()=>{} // Called after instance creation. $EL is not yet available. $EL is not yet available. BeforeDestroy :()=>{}// call before instance destruction. BeforeDestroy :()=>{}// call before instance destruction.Copy the code

Slot (slot)

The contents inside a component label are called slots. The slot is defined in the component content. Slot content can be retrieved using the Slots object. This object of slots. This object of slots. this.slots.default

<child-component>
// slot
    <template scope="props"> // props变量,用于获取插槽定义的数据
        <p slot="指定内容在插槽显示的位置">父内容</p>
        <p>{{props.msg}}</p> // props.msg=子内容
    </template>
</child-component>

Vue.component('child-component',{
    template:'<div><slot msg="子内容"></slot>
    <slot name="指定内容在插槽显示的位置"></slot></div>'
})
Copy the code

Vue usage – the router

When it comes to using HTML5’s History routing mode, Webpack-dev-server –open –history-api-fallback –config webpack.config.js

  1. NPM install –save vue-router

  2. Import and use import VueRouter from ‘vue-router’; Vue.use(VueRouter)

  3. routing

    • A static route
    const Routers =[{ path:'/index', Component :(resolve) => require(['./index.vue'],resolve)},{path:'/user/:id',// :id $route.param.id component:(resolve) => require(['./user.vue'],resolve) }, ] RouterConfig ={mode:'history'// Use html5 history routes:Routers} new Vue({router:router})Copy the code
    • Routing hop
      • <router-link to=" Router-link to the configured static route path" tag=" render tag ">In addition, the repalce attribute makes it impossible to use the back; The active-class attribute modifies the class name of the default matched route
      • Js code
    $router. Replace (' router. Path ') this.$router. Go (-1) // Go back 1 pageCopy the code
    • Navigation hooks

    You can also use the beforeEach hook for modifying the title after each jump. Execute before leaving the page. A new page can jump to the top using the afterEach hook. Run it after the page is displayed.

    Const router = new VueRouter(RouterConfig) router. BeforeEach ((to,from,next) =>{to The route object to enter the target from the current route object to leave next Go to the next hook to and from objects to get information via meta})Copy the code

Vuex usage

The core change is the use of the observer pattern, which splits the logical code and globalizes the variable data. Vuex NPM install –save vuex; import VueRouter from ‘vuex’; Vue.use(Vuex);

Const store = new vuex. store ({state:{count:0, list:[1,2,3,4,5]}, Mutations :{increment (state, can extend the base type parameter/object){state.count++; Getters :{filterList:state=>{return state.list.filter(item=>item>2)}, Getter object listCount: (state, getters) = > {return getters. FilterList. Length}}, Actions :{// incrementAsyn (context){context.com MIT ('increment')}}}) new Vue({store:store})Copy the code
  • It can be used directly on the page{{$store.state.count}}Get the value
  • Available on the pageThis. codestore.com MIT ('increment', the parameter passed in increment)Increment is a logical method defined in VUEX
  • Use it on the pagethis.$store.getters.filterListGets the filtered array
  • The actions block on the page is calledthis.$store.dispath('incrementAsyn')In addition, you can use the logical block return Promise object of the Actions block so that you can customize the callback response where it is invoked

JavaScript event loop mechanism

When calling synchronous js methods:

  1. Generate the run environment (context, containing the method’s scope, parameters, this, reference)
  2. Find the internal method, put it on the execution stack, return the result after destruction, return to the previous running environment

When calling a method that contains asynchronous JS:

  1. Generate the operating environment
  2. Find an asynchronous method, put it in a queue, and put the result in a queue. The main thread continues to execute what is in progress
  3. When the stack completes, the contents of the queue are searched
  4. Take the first ranked event and place it on the execution stack

The principle of vUE asynchronously updating dom is to listen for the change of variable value, put its value into the queue to be de-duplicated, and wait for the next loop to refresh the queue and execute. The $nextTick object immediately flushes the queue (its callback executes the response)

Virtual node

  • Normal UL LI rendering: Create a UL node and render the byte points one by one
  • Virtual node rendering: Create a virtual UL node, then create a child node of Li, and then render it again.

Manually mount the instance

Mount instances with vue. extend and $mount methods

var myComponent = Vue.extend({
    template:'<div>{{name}}</div>',
    data:()=>{
        retrun {name:'test'}
    }
})
new myComponent().$mount('#mount-div')
Copy the code

Vue support for JSX

new Vue(
    el:'#app',
    render (){
        retrun (<h1>test<h1>)
    }
})
Copy the code

Webpack basis

  • Two important and required items are Entry and Output. The entry tells WebPack where to start looking for dependencies and compile them, and the exit configures where compiled files are stored and named.
  • Output. path Specifies the output directory for packed files
  • Output. publicPath Specifies the resource file reference directory
  • Ooutput. filename Specifies the name of the output file
  • The rules of the Module object can specify a list of loaders
  • Module. test Regular representation. Every import imported CSS file encountered during compilation is converted using csS-loader and then style-loader
  • Module. use is compiled from back to front
  • Plugins are a custom plug-in feature.
  • Webpack is a JS file: webpack.config.js
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var config ={
    entry:{
        main:'./main'
    },
    output:{
        path:path.join(_driname,'./dist'),
        publicPath:'/dist/',
        filename:'main.js'
    },
    module:{
        rules:[{
            test:/\.css$/,
            use:['style-loader','css-loader']
        },{
        rules:[{
            test:/\.css$/,
            use:ExtractTextPlugin.extract({
                use:'css-loader',
                fallback:'style-loader'
            })
        }]
    },
    plugins:[new ExtractTextPlugin('mian.css')]
}
module.exports= config;
Copy the code

Install webpack and webpack-dev-server

NPM install webpack --save-dev/NPM install webpack-dev-server --save-dev // Provides the functions of starting a server, hot update, interface pitching, etcCopy the code

Install the CSS style loader

npm install css-loader --save-dev
npm install style-loader --save-dev
Copy the code

Install a plug-in that combines all CSS into one CSS

npm install extract-text-webpack-plugin --save-dev
Copy the code

Start the webpack-dev-server service script webpack-dev-server –open –config webpack.config.js

Build the environment with the command webpack –progress –hide-modules

webpack Vue Demo

  • For the built environmentNew webpack. Prod. Config. Js, while increasing"build":"webpack --progress --hide-modules --config webpack.prod.config.js"
  • Scripts command for the development environment"build":"webpack-dev-server --open --config webpack.config.js"
npm install --save vue npm install --save-dev vue-loader npm install --save-dev vue-style-loader npm install --save-dev vue-template-compiler npm install --save-dev vue-hot-reload-api npm install --save-dev babel npm install --save-dev babel-loader npm install --save-dev babel-core npm install --save-dev babel-plugin-transform-runtime npm install --save-dev babel-loader -- preset -- es2015 NPM install --save-dev babel-Runtime NPM install --save-dev url-loader // The file supports NPM Install --save-dev file-loader // image support NPM install --save-dev webpack-merge // package support NPM install --save-dev Html-webpack-plugin // Packaging supportCopy the code

Webpack.config.js module.options is further configured for different languages. Because the vue contains

var path=require('path'); var ExtractTextPlugin=require('extract-text-webpack-plugin'); var config={ entry:{ main:'./main' }, output:{ path:path.join(_dirname,'./dist'), publicPath:'/dist/', Filename :'main.js'}, module:{rules:[{test:/\. 'vue-1oader', options:{ loaders:{ css:ExtractTextPlugin.extract({ use:'css-loader', Fallback: 'vue - style - loader'}}}}, {test: / \. (GIF | JPG | PNG | woff | SVG | eot | the vera.ttf) \??. * $/, loader: 'url-loader? Limit =1024', {test:/\.js$/, loader: 'babel-loader', exclude:/nodemodules/ }, { test:/\.css$/, use:ExtractTextPlugin.extract({ use:'css-loader', Fallback :'style-loader'})}]}, plugins:[newExtractTextPlugin(" main.css ")]} module.exports = configCopy the code

Webpack.prod.config. js mainly combines the configuration of the development environment and the build environment, that is, prod is an extension of webpack.config.js

var webpack =require('webpack'); var HtmlwebpackPlugin = require('html-webpack-plugin'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var merge = require('webpack-merge'); var webpackBaseConfig =require ('./webpack.config.js'); webpackBaseConfig.plugin=[] module.exports=merge(webpackBaseConfig,{ output:{ publicPath:'/dist/', Filename :'[name].[hash].js'}, plugins:[new ExtractTextPlugin({filename:' new ExtractTextPlugin ') '[name].[hash].css', allChunks:true }), New webpack.defineplugin ({'process.env':{NODE_ENV:'"production"'}}), New webpack. Optimize. UglifyJsPlugin ({compress: {warings: false}}), / / extraction templates, New HtmlwebpackPlugin({filename:'../index_prod. HTML ', template:'./index.ejs', Inject :false})]}) //index.ejs <! DOC TYPE HTML > < HTML lang =" zh-cn "> <head> <meta charset ="UTF-8"> <title>webpack App</title> <link rel =" stylesheet" Href = "< % = htmlwebpackPlugin. Files. CSS [0] % >" > < / head > < body > < div id = "app" > < / div > < script type = "text/javascript" src="<%=htmlwebpackPlugin.files.js[0]%>"></script> </body> </html>Copy the code

The.babelrc file is created in the same directory as WebPack and writes the Babel configuration, which WebPack will rely on to compile ES6 code using Babel

{
    "presets":["es2015"],
    "plugins":["transorm-runtime"],
    "comments"false
}
Copy the code

Vue plug-in mechanism, you can add some functions globally

Prototype.$Notice = function('component-name',{}) {vue.component.prototype.$Notice = Var (){// Var (){// var (){// var (){// var (){// Var (){// Var (){// Var (){// Var () vue.use(myPlugin)Copy the code

ES6 literacy

Function (h){return h('test')} function(h){return h('test')} function(h){return h('test')}Copy the code