Vue1.0 is an MVVM framework. Upgrading to 2.0 is not an MVVM framework

Hands type

Project structures,

Cli.vuejs.org/zh/guide/in…

  1. Install @ vue/cli
yarn global add @vue/cli
Copy the code
  1. Create a project
vue create vue-demo
Copy the code
  1. Configuration (select the default option without screenshots)

Select Manually select Features

Space select a few items

And then n

  1. After the installation is complete, go to the directory
yarn serve
Copy the code

Vue. Js and vue. Runtime. Js

  • Vue. Js is a complete version with strong functions and large volume
  • Vue.runtime. js is an incomplete version with weak functions and small size
  • Webpack allows us to write code like the full version, while users download the incomplete version

SEO (Search Engine Optimization)

  • You can think of a search engine as a constant curl
  • Search engines use curl to guess the content of a page
  • Curl doesn’t get you anything if you create div pages with JS

So what?

  • theTitle, description, keyword, H1, aCan be written
  • Rule: Make curl get the information on the page
  • SEO will work

Vue construction options

Create an instance

const vm = new Vue(options)
Copy the code
  • The VM object encapsulates all operations on the view, including data reads and writes, event binding, and DOM updates
  • The constructor of a VM is Vue, and in ES6 parlances, the class to which the VM belongs is Vue
  • Optioins are parameters to new Vue, commonly referred to as options or construct options

What are the options

  1. Data:Data, props, propsData, computed, Methods, Watch
  2. DOM: El, Template, render, renderError
  3. Lifecycle hooks:BeforeCreate, created, beforeMount, Mounted, BeforeUpdate, UpdatedActivated, Deactivated, beforeDestroy, destroyed, errorCaptured
  4. Resources:Directives, filters, components
  5. Combination:Parent (uncommon), mixins (mixed), extends (extended), provide (provided), inject (injected)
  6. Others: Don’t look
  • el: mount point, which is substituted with $mount
new Vue({ el: "#id", render: (h) => h(Demo), }); Equivalent to the new Vue ({render: (h) = > h (Demo),}). $mount (" # id ");Copy the code
  • data: Internal data

Two ways to write it:

  1. object
new Vue({
    data: {
        n:0
    }
}),
Copy the code
  1. function
new Vue({
  data() {
    return {
      n:0
    }
  },
Copy the code

Functions are preferred; if it is a.vue ending file (i.e., a Vue component), its data can only be a function

  • methods: event handler or a normal function

For example,

methods: { add() { this.n += 1; }},Copy the code
  • componentsComponents:

There are three ways to create a component

Experience:

  • Method 1 is preferred
  • The file name should be all lowercase
  • The component name should start with a capital letter

Method 1: Create a.vue file

import Demo from './demo.vue' const vm = new Vue({ components:{Demo}, template: ` <Demo/> `, }); // const vm = new Vue({render: (h) => h(Demo); });Copy the code

Method two: use JS way

Vue.component("#Demo2", {
  template: `
    <div> demo22222</div>
  `,
});
Copy the code

Method three: combine the two

const vm = new Vue({
  components: {
    wbs: {
      template: `
        <div>demo3333</div>
      `,
    },
  },
  template: `
  <wbs/>
  `,
});
Copy the code

Four hook

  • createdThe instance appears in memory, inconsole.log()In front of thedebuggerTake a look at the page changes for proof
Created (){console.log(' this thing appears in memory, not in pages ')}Copy the code
  • mountedThe instance appears on the page, inconsole.log()In front of thedebuggerTake a look at the page changes for proof
/ / mounted() {console.log() {console.log(); }Copy the code
  • updatedThe instance is updated
Updated () {console.log(" updated "); }Copy the code
  • destroyedThe instance dies

Props: Accepts external properties

In the demo. Vue statement

<script>
  export default {
    props:['message']
}
Copy the code

In the main. Js references

new Vue({ template: '<div> <Demo message=' hello '/> <Demo message='n'/> // is passed n <Demo :message='n'/> // with colon, </div> ',}).$mount("# WBS ");Copy the code

A colon is added to indicate that the quotes are JS code, and the arguments can be functions

Vue data responsive

gettersetter

Let obj1 = {name: "gao ", name:" yuanyuan ", age: 18,}; Let obj1 = {last name: "gao ", last name:" yuan yuan ", last name () {return this. Name + this. }, age: 18, }; Console. log(" Requirement 1 :" + obj1. name ()); Let obj2 = {family name: "high ", family name:" yuan yuan ", get name () {// this is different here. Name + this. }, age: 18, }; Console. log(" Requirement 1 :" + obj1. name); Let obj3 = {family name: "high ", family name: "", get family name () {return this. Name + this. }, set name (XXX) {this. name = XXX [0]; This. The name = XXX. The substring (1); }, age: 18, }; Console. log(' Requirement 3: last name ${obj3. Last name}, first name ${obj3. Name} `);Copy the code

Object.defineProperty

DefineProperty is the only way to add a get or set to an Object. DefineProperty does not exist

let _xxx = 0; Object.defineProperty(obj, "xxx", { get() { return _xxx; }, set(value) { _xxx = value; }});Copy the code
  • Object.defineProperty(obj,'n',{... })Add a virtual property n to obj object
  • Object.defineProperty(obj,'n',{value:0})Add a virtual attribute n to obj with a value of 0

If n is not passed, there will be a bug, there are two solutions

  • Vue.set()
  • this.$set()
  • role
  • The new key
  • Automatically create agents and listeners

Proxy and Monitor

vm = new Vue({data: myData})

  • vmismyDataThe agent of(proxy)
  • tomyDataMonitor all properties of the
  • Why? To prevent itmyDataThe properties of,vmI don’t know
  • vmWhat does it matter if you know?
  • You can call it when you know the property has changedrender(data).UI=render(data)It automatically refreshes
Let data1 = {} object.defineProperty (data1, 'n', {value: 0}) console.log(' request 1: ${data1.n} ') Data2.n = -1 should not be valid, Let data2 = {} data2._n = 0 // _n is used to steal n values object.defineProperty (data2, 'n', {get(){return this._n}, set(value){if(value < 0) return this._n = value}}) console.log(' requirement 2: ${data2.n} ') data2.n = -1 console.log(' Requirement 2: ${data2.n} 'failed to set to -1) data2.n = 1 console.log(' Requirement 2: ${data2.n}') data2.n = 1 console.log(' Requirement 2: ${data2.n} set to 1 success ') // What if the other side uses data2._n directly? // Requirement 3: Function proxy({data :{n:0}){const obj = {} // let data3 = proxy({data :{n:0}}) // Theoretically you should iterate through all the keys of data, Object.defineproperty (obj, 'n', {get(){return data.n}, Set (value){if(value<0)return data.n = value}}) return obj // obj is the proxy} // data3 is obj console.log(' 表 三 : ${data3.n} ') data3.n = -1 console.log(' requirement 3: ${data3.n} ', set to -1 failed ') data3.n = 1 console.log(' Requirement 3: ${data3.n} ', set to -1 failed ') ${data3.n}, set to 1 successful ') let myData = {n:0} let data4 = proxy({data:myData}) // data3 is obj console.log(' bar precision: ${data4.n} ') mydata.n = -1 console.log(' bar precision: ${data4.n} ') ? '// Demand 5: Let myData5 = {n:0} let data5 = proxy2({data:myData5}) Function proxy2({data}){function proxy2({data}){ Let value = data.n object.defineProperty (data, 'n', {get(){return value}, Set (newValue){if(newValue<0)return value = newValue}}) Const obj = {} object.defineProperty (obj, 'n', {get(){return data.n}, Set (value){if(value<0)return data.n = value}}) return obj // obj is the proxy} // data3 is obj console.log(' 表 5: ${data5.n} ') mydata5.n = -1 console.log(' Requirement 5: ${data5.n} ', set to -1 failed ') mydata5.n = 1 console.log(' Requirement 5: ${data5.n} ') mydata5.n = 1 console.log(' Requirement 5: ${data5.n} ') // let data5 = proxy2({data:myData5}) // let vm = new Vue({data: myData})Copy the code

conclusion

The new key in the object

  • VueThere is no way to eavesdrop and proxy in advance
  • In order to usesetTo addkeyTo updateUI
  • It’s best to write the attributes out in advance, not add themkey
  • But arrays can’t do “not newkey

Variable method in Vue array

The new key in the array

  • Can also be usedsetTo addkey, and create listeners and proxies, updateUI
  • You Yuxi tampered with 7APISo we can add and delete arrays
  • These sevenAPIListeners and proxies are handled automatically, and U is updated
  1. push()
  2. pop()
  3. shift()
  4. unshift()
  5. splice()
  6. sort()
  7. reverse()

The computed and Watch

Computed properties

The calculated property is the calculated property

Code examples:

New Vue({data: {user: {email: "[email protected]", nickname: "niu niu ", phone: "99999999",},}, computed: DisplayName: {get() {const user = this.user; return user.nickname || user.email || user.phone; }, set(value) { console.log(value); this.user.nickname = value; }, }, }, template: ` <div> {{displayName}} <div> {{displayName}} <button @click="add">set</button> </div> </div> `, methods: { add() { console.log("add"); This. displayName = "cow "; }, }, }).$mount("#app");Copy the code

The cache

  • If the dependent properties have not changed, no recalculation will take place
  • getter/setterIt doesn’t cache by default,VueWe did a special treatment

Watch to monitor

  • When the data changes, a function is executed
  • Watch is an asynchronous function
  • Do not write arrow functions in watch

So what are data changes?

  • objUsed to be{a:'a'}Now,obj= {a:'a'}.
  • objchanged
  • obj.aDid not change
  • Simple types look at values, complex types (objects) look at addresses and that’s the rule for ===

deep:true

  • ifobject.aB: Yes, pleaseobjectIt also changes
  • If it isdeep:true, thenobjWill become
  • If it isdeep:false, thenobjI haven’t changed

Immediate: true runs the Watch function on the first render, which is not run by default

Templates, directives, modifiers

3 and 6 are equivalent

expression

  • {{ object.a }}expression
  • {{ n +1 }}You can write any operation
  • {{ fn(n) }}You can call a function
  • If the value isundefinednullDon’t show

v-text

Example:

< span v - text = "MSG" > < / span > is equivalent to the < span > {{MSG}} < / span >Copy the code

v-html

  • Assuming thatdata.xA value of<strong>hi</strong>
<div v-html="x"></div> will display the bold 'hi'Copy the code

v-pre

  • show{{ n }}
  • v-preTemplates are not compiled
<div v-pre>{{ n }}</div>
Copy the code

v-bind

<img v-bind: SRC ="x" /> Short <img: SRC ="x" /> Bind class <div :class="[classA, </div> <div :style="{fontSize: size + 'px'}"></div>Copy the code

v-on

<button V-on: click= "add ">+1</button> n+=1 <button V-on: Click = "n + = 1" > XXX < / button > abbreviations: < button@click ="add" >+1</button> Stop bubbling < button@click. stop="doThis"></button> Prevent default behavior <button @click.stop.prevent="doThis"></button>Copy the code

v-for

  • Grammar:For (value,key) in Object or array
  • appearv-for, be sure to add at the end:key
<div v-for="(item, index) in items" :key="index"></div>
<div v-for="(value, key) in object" :key="index"></div>
Copy the code

v-show

<div v-show="n%2===0">n is even </div>Copy the code

The modifier

Prevents event propagation/bubbling

@click.stop="add"
Copy the code

Disables the default action

@click.prevent="add"
Copy the code

It means both at the same time

@click.stop.prevent="add"
Copy the code

Just keep the following four in mind for now

  • .stop
  • .prevent
  • .sync
  • keypress.enter

The sync modifier

  • Vue rule: Components cannot be modifiedpropsExternal data
  • Vue rules:this.$emitCan trigger events and pass parameters
  • Vue rules: $eventYou can get$emitThe parameters of the
:money. Sync ="total" equivalent to :money="total" V-on :update:money="total = $event"Copy the code

Advanced construction properties

Directive instruction

You can reduce the repetition of DOM operations

  1. Declare a global directive

Such as:

Vue.directive('x',{
  inserted: function (el) {
    el.addEventListener('click',()=>{console.log('x')})
  },
})
Copy the code
  1. Local declarations
new Vue({ ... , directive:{ 'x':directiveOptions } })Copy the code

DirectiveOptions has five function properties, do not need to recite, use the documentation

bind: function () {},
inserted: function () {},
update: function () {},
componentUpdated: function () {},
unbind: function () {}
Copy the code

Bind and inserted are generally used

The custom V-on2 directive listens for click events

new Vue({ directive: { on2: { inserted(el, info) { el.addEventListener(info.arg, info.value); }, unbind(el, info) { el.removeEventListener(info.arg, info.value); },},}, template: '<button v-on2:click='hi> I </button>', methods: {hi() {console.log(hi); ,}}});Copy the code

Mixins with

Reduce duplication of data, methods, and hooks

IO /s/brave-dij…

Extents inheritance

The requirements are similar to mixins

Provide Provides and inject

Need: one click skin, change text size

The code examples codesandbox. IO/s/fragrant -…

provide(){} 
inject: []
Copy the code
  • Functions: Large range of data and method, etc
  • Note: You cannot pass themeName without passing changeTheme, because the value of themeName is copied to provide

The form and v – model

Official documentation cn.vuejs.org/v2/guide/fo…

The form

<form @submit. Prevent ='onSubmit'> <label > <span> <span> <input type="text" V-model ='user.name'> </label> <label > </span> <input type="text" V-model ='user.password'> </label> <button type="submit"> </button> </form>Copy the code

Three modifiers

  • .lazy
  • .number
  • .trim

. Number Converts the entered value to a number

<input v-model.number="age" type="number">
Copy the code

Trim Trim the leading and trailing Spaces

<input v-model.trim="msg">
Copy the code

V – the nature of the model

Value ='user.username' @input='user.name= XXX =$event.target.value'Copy the code

Ant Design of Vue

Antdv.com/docs/vue/ge…

Vue Router Front-end routing implementation

What is a route?

Routing is the thing that distributes requests, showing users the page they want based on the request they send

  • The default route is not entered by the user# NumbersWhen we set the default to go# 1,# 2.
  • The 404 route is entered in a book#xxIf not, set redirect to 404 page
  • Nested routines consist of, for example# 1.1We first render 1 with layer 1 route, then render 1 with layer 2 route.

Hash, History, and Memory modes

The browser will not send the content after # to the server

  • Hash can be used in any case, but SEO is not friendly and the server does not receive hash
  • History, which can be used only when the back end renders all front-end routes to the same page (excluding the 404 page). Internet Explorer 8 does not support this option
  • Memory stores the path to localStorage

Vue animation principles

transition

  • .fade-enterThe first frame fades in
  • .fade-enter-activeFade in
  • .fade-enter.fade-leave-toGenerally used together

Bootcdn search velocity

A list of animation

The transition – the group TAB