Source: making power button (LeetCode) | | to brush the topic card for stars ✨ | give a ❤ ️ attention, ❤ ️ thumb up, ❤ ️ encourages the author

[Opened] Task 1: Brush the question punch card * 10

Hello everyone, I’m Nezha. Nice to meet you ~~

Nezha’s life creed: If you like what you learn, there will be strong motivation to support it.

Learn programming every day, so that you can get a step away from your dream. Thank you for not living up to every programmer who loves programming. No matter how strange the knowledge point is, work with me to calm down the wandering heart and keep going. Welcome to follow me vx:xiaoda0423, welcome to like, favorites and comments

Time: March 1 ~ March 13

  • Force buckle (LeetCode)- Sum of two numbers, valid parentheses, sum of two numbers | brush questions punch card – March 1
  • LeetCode – Merges two ordered lists, removes duplicates in sorted arrays,JavaScript Notes | Flash cards – March 2
  • Force Button (LeetCode)- Maximum suborder sum,JavaScript Data Structures and Algorithms (Arrays) | Brush questions punched -3 March
  • Say something about CSS | Tech Review – March 4
  • Force Buckle (LeetCode)- Stack, parenthesis generation | brush questions punch card – 5 March

preface

If this article is helpful to you, give ❤️ a follow, ❤️ like, ❤️ encourage the author, accept the challenge? Article public account launch, concern programmer Doraemon first time access to the latest article

❤ ️ cartridge ❤ ️ ~

Vue cross-platform development

Use Vue to develop the whole process of the mall interface design, such as home page, product display, shopping cart, order, membership interface, etc. (Homepage development, user management, product implementation, news page, shopping, and order processing)

  1. Vue.js introduction, data binding, forms and two-way data binding, conditional and circular directives, style binding, event handlers, listeners, and computed properties.
  2. Vue.js components, custom instruction and response interfaces, routing, animation and transitions, plug-ins in Vue.js Axios.

Vue.js basic syntax, data binding, form usage, conditional and loop directives, style binding, event handling, listening and evaluating properties, etc.

  1. Vue.js is a set of progressive frameworks for building user interfaces.
  2. Vue focuses only on the view layer and adopts a bottom-up incremental development design.
/ / reference Vue. Js code < script SRC = "https://unpkg.com/vue/dist/vue.js" > < / script > / / sample < body > / / display code < div id = "app" > < p > {{message}} < / p > < / div > / / script code < script > new Vue ({el: '# app, data: {message:' hello Lord which zha '}}) < / script > < / body >Copy the code

I don’t know if you have them on your computer, but I have them on my computer: WebStorm, Eclipse, PhpStorm, Vscode, HBuider, etc.

There are three ways to install vue.js:

  • Use the CDN method
  • Download the official vue.js framework
  • NPM method

Based on 2.x Vue:

// create A new project based on webpack template vue init webpack my-project // project name my-project // project description A Vue. Js project // Use esline-yes // yes... // Go to the project CD my-project CNPM install CNPM run devCopy the code

Vue. Js began

Each Vue application needs to be implemented by instantiating the Vue.

Example:

Var vm = new Vue({// options})Copy the code
<h1>{{dada}}</h1> // data: { dada: 'jeskson' }

<h2>{{use()}}</h2> 

methods: {
 use() {
  return this.dada
 }
}
Copy the code
  • dataUsed to define attributes
  • methodsUsed to define functions
  • {{}}Used to output object properties and function return values

1. V-text Outputs plain text. 2. V-html Outputs parsed text

The V-once directive, which indicates that elements and components are rendered only once and do not change as data changes

V – cloak instructions

V-cloak does not require an expression and will be removed from the bound HTML element when the Vue instance finishes compiling. The V-cloak directive is often used in conjunction with display: None.

Example:

< div id = "app" v - cloak > < div: style = "{' color: color, 'fontSize: fontSize +' px '}" > < / div > text {{message}} < / div > new Vue ({el: '# app' data: {color: 'red', fontSize: '12' message: 'Lord which zha'},})Copy the code

When the network speed is slow and the Vue. Js file is not finished loading, the page will display {{message}}. DOM will not be replaced until Vue creates the instance and compiles the template, during which the screen will flash.

Using CSS:

<style type="text/css">
 [v-cloak] {
  display: none
 }
</style>
Copy the code

Example:

// Bind an attribute <img V-bind: SRC ="imgSrc"> // abbreviation <img: SRC ="imgSrc"> // inline string concatenation <img: SRC ="'/path/img/'+fileName"> // class binding <div :class="{ red: isRed }"></div> <div :class="[classA,classB]"></div> <div :class="[classA, { classB: isB, classC: <div :style="{fontSize: Size + 'px'}"></div> <div :style=" styleObjectA, styleObjectB]"></div> someProp, 'other-attr': <div V-bind: text-content-prop ="text"></div> // prop binding, Prop must declare < my-Component :prop="someThing"></my-component> // pass props of the parent to the child <child-component via $props v-bind="$props"></child-component>Copy the code

Support for JavaScript expressions

Example:

<div>{{number+2}}</div> <div>{{ da ? 'show' : 'don't show'}} < / div > < div > {{arr. Split (' '). The reverse () join (' ')}}Copy the code

Summary of vue.js directive

  • v-model, bind data
<input v-model="message">
Copy the code
  • v-text, output text, cannot parse labels
<p v-text="message"></p>
Copy the code
  • v-html, output text, parse labels
<p v-html="message"></p>
Copy the code
  • v-once, bind data only once
<p v-once>{{message}}</p>
Copy the code
  • v-bind, bind attributes
<img v-bind:src="imgurl">
Copy the code
  • v-if, controls whether to display the container, converts the value to a Boolean value, and comments the container when false; Is displayed when true
<div v-if="true"></div>
Copy the code
  • v-showControls whether the container is displayed when set to true and not when set to false
<div v-show="true"></div>
Copy the code
  • v-for, loop through the number group, object
<li v-for="(val,key) in arr">{{val}}</li>
Copy the code
  • v-cloakHiding elements before the Vue code is executed solves the flicker problem
<p v-cloak>{{message}}</p>
Copy the code

Instructions for

  • v-bindandv-onExample:
<a v-bind:href="url"></a>

<a :href="url"></a>

<a v-on:click="doSomething"></a>

<a @click="doSomething"></a>
Copy the code

The modifier

Modifiers are special suffixes indicated by a semicontal period “.”, used to indicate that an instruction should be bound in a special way.

  • .preventDecorator:v-onDirectives are invoked for triggered eventsevent.preventDefault()

Example:

<form v-on:submit.prevent="onSubmit"></form>
Copy the code

The form

The V-model directive is used to create two-way data binding on input, SELECT, Textarea, checkbox, radio and other form control elements, automatically updating the bound element’s value based on the value on the form.

<input v-model="test">

<input :value="test" @input="test = $event.target.value">
Copy the code
  • @inputIs the<input>Listening for input events

Select the use of

<div id="app"> <select V-model ="dada" name="shuiguo"> <option value="0"> Please select </option> <option value="p"> Apple </option> < option value = "x" > banana < option > < option value = "l" > litchi < option > < / select > < span > default: {{dada}} < / span > < / div > data: {dada: 'x' }Copy the code
  • checkbox

Example:

<div id="app"> <input type="checkbox" v-model="dada" id="da"> <label for="da">{{dada}}</label> </div> <div id="app"> <input type="checkbox" V-model ="city" value=" shenzhen "> Shenzhen <input type="checkbox" V-model ="city" value=" Beijing "> Beijing <input Type = "checkbox" v - model = "city" value = "Shanghai" Shanghai > < br > < label for = "" > {{city}} < / label > < / div >Copy the code
  • radio

Example:

<div id="app"> <input type="radio" V-model ="moren" value=" male "> male <input type="radio" v-model="moren" value=" female "> female // <span>{{moren}}</span> </div>Copy the code
  • aThe label

Example:

< div id = "app" > < : a: href = "url" target = "target" > Lord which zha < / a > < br > < / div > new Vue ({el: '# app, data: {url: 'http://www.dadaqianduan.cn', target: '_blabk' } })Copy the code

Use of filters, examples

{{ message | capitalize }}
<div :id="rawId | formatId"></div>
Copy the code

Get the data to submit for the form:

<form @submit. Prevent = "submit">Copy the code

Example:

<div class="hello"> <ul> <form @submit.prevent="submit"> <input type="text" name="name" v-model="inputtet.name"> <input Type =" name="password" v-model="inputtext. Password "> <input type=" value=" submit" > </form> </ul> </div> <script> var vm = new Vue({ el: '.hello', data: { inputtext: {} }, methods: { submit() { ... } }, }) </script>Copy the code

Modifier of the V-model directive

Such as:

  • v-model.lazyOnly if theinputAn input field occursblurEvent
  • v-model.number, converts the string entered by the user into a number
  • v-model.trimTo remove the Spaces before and after user input

Example:

<input v-model.lazy=" MSG "> <input v-model.lazy=" number" > HTML input elements always return the string <input V-model. number="age" type="number"> // trim <input V-model. trim=" MSG ">Copy the code

V-if instruction, V-show instruction, V-for instruction

  1. v-if.v-else.v-else-ifinstruction

V-else, V-else -if must come after v-if or V-else -if

  1. v-showCommand to determine whether the block in which it is displayed or not

Example:

V - show = "true or false"Copy the code
  • trueBlock display
  • falseThe block is not displayed

If the value is set to display: None, the element still exists in the DOM tree. If the value is set to false, the element is removed from the DOM tree

  1. v-forInstruction used to iterate over a set of numbers or objectsdataDynamically refresh view of data in

When v-for is used to render data, the key attribute should be added to ensure that the value of this key is unique and not repeated. The function is to uniquely identify each item of data and improve rendering performance.

Example:

V -for="value in obj" v-for="value in obj" v-for="value in obj" v-for="(value, key, index) in obj"Copy the code

Note: you cannot refresh the view dynamically, either by using the length property of the array to change the array, or by using the index to change the array.

Vue. Set (arr, index, value), where arr represents the array to be set, index represents the array index, and value represents the new value of the index item. Vue. Set (vm.list, 0, {id: 1, name: ‘jeskson’}}, or call the array’s splice() method.

Example:

< div v - for = "x in [1, 2, 3, 4]" > {{x}} < / div > < div v - for = "y in arr" > {{y}} < / div > < div id = "app" > < template v - for = "item in arr" > {{item}} </template> </div>Copy the code
  • object

Example:

V - for = "alias object in" < div id = "app" > < div v - for = "item in obj" > {{item}} < / div > < / div > v - for = "(value, key) in obj" <div v-for="(value, key) in obj"> {{key}} : {{value}} </div> v-for="(value, key, index) in obj"> <div v-for="(value, key) in obj"> {{index}}.{{key}} : {{value}} < / div > / / can also cycle show integer n - the for = "n in 10" < div v - for = "n in 10" > {{n}} < / div >Copy the code

Implement the multiplication table

Example:

< div id = "app" / / outer loop < div v - for = "x 9" in > / / inner loop < div v - for = "y in x" > {{y}} * {{x}} = {{x * y}} | < / div > < / div > < / div >Copy the code

Style binding

Property binding, object binding, array binding

Example:

<div :class="{dadastyle: isActive}"></div> <script> new Vue({ el: '#app', data: { isActive: true } }) </script> <div :class="{dastyle: isActive, jj: HasError}"></div> // Bind an object in the data <div :class="classObject> Nezha </div>Copy the code

Inline style style

Example:

:style="{style 1, style 2, style n}" style="font-size: 10px; :style="{color: 'red',fontSize: '10px'}" css1: {fontSize:"10px"}, css2: {color: "red"} < div: style = "[css1 and css2]" > Lord which zha < / div >Copy the code

Ternary operator

Example:

Expression? <div :class="[isActive? ActiveClass: "]"></div>Copy the code

The event processing

  • v-onInstruction binding clickclickThe event
  • @click="say()"
  • @click="num += 1"
  • @click="add"
  • @click="add(x1,x2)"

Event modifier

Example:

<a @click.stop="doThis"> </ A > // Submit events no longer reload the page <form @submit. Prevent ="onSubmit"></form> // Modifiers can be connected in series < A @click.stop.prevent="doThis" </a> // Only modifiers < form@submit. Prevent ></form> // Add event listeners using event capture mode <div <div @click.self="doThis"> </div> // The click event can only be clicked once <a @click.once="doThis"></a>Copy the code

Key modifier:

< [email protected]="submit"> < input@keyup. Enter ="submit"> .enter, .tab, .delete, .esc, .space, .up, .down, .left, .right, .ctrl, .alt, .shif, .metaCopy the code

Listen on and evaluate properties

  • watchA listener property that monitors changes to data and triggers the corresponding callback function execution.
  • throughvmThe object’s$watch()orwatchConfigure to monitor the specified properties.
  • When the property changes, the callback function is called automatically and evaluated inside the function.
  • newVal, the value of the changed data.
  • oldVal, the value before the data changes.

Example:

{this.qianmi (val) {this.qianmi = val; this.mi = val*1000; }, mi(val) { this.mi = val; this.qianmi = val/1000; }} km: <input type="text" V-model ="qianmi"/>Copy the code

The shopping cart

Example:

// Increase and decrease the number of products in the shopping cart // the total price of the shopping cart changes accordingly // The number of products in each shopping cart is also clear 0 operation, and the total price of the shopping cart also changes accordingly. "iphone 6", jiage: 1000, shuliang: 1 }, { id: 2, mingcheng: "iphone 7", jiage: 2000, shuliang: 1 } ] totalMoney() { var money = 0; // initialize for(var x = 0; x < this.shoujiarr.length; x++) { money = money + this.shoujiarr[x].jiage * this.shoujiarr[x].shuliang; } return money; // Return value}Copy the code

Example:

<! DOCTYPE HTML > < HTML > <head> <meta charset=" UTF-8 "> <title> Listen attributes - simple shopping cart </title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <style type="text/css"> table { border: 1px solid black; width: 100%; text-align: center; } th { height: 50%; } th, td { border-bottom: 1px solid #ddd; } </style> </head> <body> <div id="app"> <! -- Define shopping cart table --> <table> <! - the title section - > < tr > < th > serial number < / th > < th > commodity name < / th > < th > commodity prices < / th > < th > purchase quantity < / th > < th > action < / th > < / tr > <! -- shoujiarr --> <tr v-for="item in shoujiarr"> <td>{{item.id}}</td> <td>{{item.mingcheng}}</td> <td>{{item.jiage}}</td>  <td> <! < button@click ="item.shuliang=item.shuliang-1"> - </ button@click ="item.shuliang=item.shuliang-1" @click="item.shuliang=item.shuliang+1"> </button> </td> <td> </button @click="item.shuliang=item.shuliang+1"> {{totalMoney()}}</div> </div> <script> var vm = new Vue({el: '#app', data: {shoujiarr: [{id: 1, mingcheng: "iphone 6", jiage: 1000, shuliang: 1 }, { id: 2, mingcheng: "iphone 7", jiage: 2000, shuliang: 1 } ] }, methods: { totalMoney() { var money = 0; // initialize for (var x = 0; x < this.shoujiarr.length; x++) { money = money + this.shoujiarr[x].jiage * this.shoujiarr[x].shuliang; } return money; </script> </body> </ HTML >Copy the code

Effect:

Select all and deselect all

  • Click All to check all the boxes
  • Click Deselect all to deselect all

Example:

<! DOCTYPE HTML > < HTML > <head> <meta charset=" UTF-8 "> <title> Listen to attributes - select </title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <style type="text/css"> </style> </head> <body> <div id="app"> <! <input type="checkbox" id="ckbox" @change="ckall()" V-model ="checked"/> <label for="ckbox"> <label ><hr> <input type="checkbox" id="baidu" value="baidu" v-model="jieguo"/> <label for="baidu">baidu</label> <input type="checkbox" id="taobao" value="taobao" v-model="jieguo"/> <label for="taobao">taobao</label> <input type="checkbox" id="qq" value="qq" v-model="jieguo"/> <label for="qq">qq</label> <hr> {{jieguo}} </div> <script> var vm = new Vue({ el: #app', data: {checked: false, // Initialize jieguo: [], // initialize shuzu: ["baidu"," Taobao "," QQ "]}, methods: Jieguo = this.shuzu}else{// Cancel jieguo = []}}, watch: { "jieguo"() { if(this.jieguo.length == this.shuzu.length) { this.checked = true }else{ this.checked = false } } } }) </script> </body> </html>Copy the code

Calculate attribute

Computed properties include computed,methods, and setters.

  1. incomputedProperties object defines methods for evaluating properties, used on the page{{method name}}To display the results
  2. throughgetter/setterTo display and monitor property data
  3. The calculated properties are cached and are read only oncegetter
  4. Calculated properties are recalculated when their dependent property values change

Example:

Computed: {// Calculate getter reversedMessage() {return this.message.split(" ").reverse().join(" ")}}Copy the code

Example:

<! DOCTYPE HTML > < HTML > <head> <meta charset=" UTF-8 "> <title> </title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <style type="text/css"> </style> </head> <body> <div Id ="app"> <p> Original string: {{message}}</p> <p> Computed reversed string: {{reversedMessage}}</p> <hr> {{message.split('').reverse().join('')}} </div> <script> var vm = new Vue({ el: '#app', data: {message: 'hello'}, // Calculate attributes block computed: {return this.message.split('').reverse().join('')}}, methods: {}, watch: {// Calculate properties of getter reversedMessage() {return this.message.split('').reverse().join(")}}, methods: {}, watch: { } }) </script> </body> </html>Copy the code

Effect:

  • methods
  1. computedBased on its dependency cache, the value is reevaluated only if the dependency changes.
  2. usemethodsThe function is always called again during re-rendering.

Example:

<! DOCTYPE HTML > < HTML > <head> <meta charset=" UTF-8 "> <title> </title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <style type="text/css"> </style> </head> <body> <div Id ="app"> <p> Original string: {{message}}</p> <p> reversedMessage}}</p> <hr> <p> {{reversedMessage2()}}</p> </div> <script> var vm = new Vue({ el: '#app', data: { message: 'hello'}, // Calculate attribute block computed: ReversedMessage () {return this.message.split('').reverse().join('')}}, methods: { reversedMessage2() { return this.message.split('').reverse().join('') } }, watch: { } }) </script> </body> </html>Copy the code

setter

When the page gets some data, it will look in the data, can not find to find in the calculation of the property, in the calculation of the property to get data will automatically execute the get method, but also provides a set method.

Example:

computed: {
 site: {
  // getter
  get() {
   return this.name + ' ' + this.url
  },
  set(newValue) {
   var names = newValue.split('|')
   this.name = names[0]
   this.url = names[names.length-1]
 }
}
Copy the code

Example:

<! DOCTYPE HTML > < HTML > <head> <meta charset=" UTF-8 "> <title> </title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <style type="text/css"> </style> </head> <body> <div Id = "app" > < p > {{site}} < / p > < / div > < script > var = new vm Vue ({el: '# app, data: {name:' at the front, url: 'http://www.dadaqianduan.cn'}, / / computation attribute block computed: {site: { //getter get() { return this.name + ' ' + this.url }, //setter set(newValue) { var names = newValue.split('|') this.name = names[0] this.url = names[names.length-1] } } }, Methods: {}, watch: {}}) vm. Site = 'dada front-end | http://www.dadaqianduan.cn; document.write('name:' + vm.name); document.write('<br>'); document.write('url:'+vm.url) </script> </body> </html>Copy the code

Effect:

Learn how to improve: Learn how to use components, custom instructions, response interfaces, routing, transitions and animations, and third-party add-on Axios.

component

  • Global components
  • Local components
  • The props property of the component
  • Dynamic props of a component

General registration:

Vue.component(tagName, options) Vue.component(tagName, options) Vue.component(tagName, options)Copy the code

Vue constructor:

Var componentcontent = vue.extend ({template: '<div> custom global component, use vue.extend </div>'}) vue.componentcontent (" componentname ", componentcontent)Copy the code
  • Vue.extend()isVueConstructor extension, calledVue.extend()You create a component constructor, not a concrete component instance.
  • Vue.extend()The constructor has an option object, the option objecttemplateProperty is used to define what the component will renderHTML.
  • useVue.component()When registering a component, you need to provide: a label for the component and a component constructor. This method internally calls the component constructor to create a component instance, which takes effect only when it is mounted to a Vue instance.

Component example usage

Vue.component('dada', {template: '<h1> '}} // Create a component constructor - var da = vue.extend ({template: '<h1> Nezha, custom global component, Using the Vue. The extend < / h1 > '}) Vue.com ponent (' dada2, da) / / using the component < div id = "app" > < dada > < / dada > < dada2 > < / dada2 > < / div >Copy the code

Local components

Local registration is implemented using the Components property.

Var demoObj = {template: '<h1> Components'; var demoObj = {template: '<h1> Components'; <div id="app"> <demoObj></demoObj> </div>Copy the code

Props attribute

  • propsAre certain custom properties that the parent uses to pass data
  • The parent component’s data passespropsProperty to child components
  • The child component is explicitly usedpropsOption statementprops

Dynamic props

Example:

Vue.component('child', {
 props: ['myvar'],
 template: '<h1>{{myvar}}</h1>'
})
Copy the code

Custom instruction

Vue specifies the command syntax as follows:

Directive (id, definition) // id is the directive ID, definition is the definition objectCopy the code

Register a global custom directive V-focus:

Inserted (el) {// Focus el.focus()}})Copy the code

Effect:

Example:

<! DOCTYPE HTML > < HTML > <head> <meta charset=" UTF-8 "> <title> Listen attributes - custom directive </title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <style type="text/css"> </style> </head> <body> <div Id ="app"> <p> When the page loads, the input element automatically gets focus: </p> <input v-focus> </div> <script> // Register a global custom directive vue. directive('focus', Inserted (el) {// Focus element el.focus()}}) var vm = new Vue({el: '#app', data: {}, // Calculate attribute block computed: { }, methods: { }, watch: {} }) </script> </body> </html>Copy the code

Hook function

  1. bindWhen the instruction is first bound to an element, you can use this hook function to define an initialization action that is performed once at binding time.
  2. insertedCalled when the bound element is inserted into the parent node.
  3. updateIs called when the template to which the bound element belongs is updated, regardless of whether the binding value changes. Unnecessary template updates can be ignored by comparing the binding values before and after the update.
  4. componentUpdatedCalled when the template to which the bound element belongs completes an update cycle.
  5. unbind, called only once, when an instruction is unbound from an element.

Arguments to the hook function

  • el, which can be used to manipulate the DOM directly

Vue. Js response interface, Vue can add data dynamic response interface.

Example:

vm.$watch('counter', function(nval, oval){
 alert();
});
Copy the code

Vue.set

This method is used to set the properties of the object, to solve the problem that Vue cannot detect the added properties

Vue. Set (target, key, value) // Target object or array. Key can be a string or a number, and value can be any typeCopy the code

Example:

<div id="app"> <p style="font-size: 23px;" < p style=" max-width: 100%; clear: both; min-height: 1em; </button> </div> <script> var myproduct = {"id": 1, name: "jeskson", "price": "12"}; var vm = new Vue({ el: '#app', data: { counter: 1, products: myproduct } }); Vue.set(myproduct, 'dada', 1); </script>Copy the code

Vue.delete

Use to remove dynamically added properties

Vue. Delete (target, key) Vue.delete(myproduct, 'price');Copy the code

vue-router

Using a mirror:

cnpm install vue-router
Copy the code

HTML code:

<div id="app"> <h1> <p> <router-link to="/foo"> </router-link to="/bar"> </router-link> </p> <router-view></router-view> </div>Copy the code

JavaScript code:

Use (VueRouter) // Define component const Foo = {template: '<div> Foo </div>'} const Bar = {template: Const routes = [{path: '/foo', Component: foo}, {path: '/bar', Component :Bar}] // Create router instance const router=new VueRouter({routes}) // Create and mount root instance const app =new Vue({router} }).$mount('#app')Copy the code

< the router – the link > component properties, such as to replace, append, tag, active – class, exact – active – class, event, etc.

To represents the link to the destination route. After clicking the link, the value of to is passed to router.push().

<router-link to="home"> home </router-link> // render result <a href="home"> home </router-link> <router-link :to="{path:'home'}"> home </router-link> <router-link :to="{name:'user',params:{userId: 123}}">User</router-link> <router-link :to="{path: 'register', query: { name: 'jeskson'}}">Register</router-link>Copy the code

Replace property, which calls router.replace() instead of router.push() when clicked, and leaves no history after navigation

<router-link :to="{path: '/dadaqianduan'}" replace></router-link>
Copy the code

Append set, add base path before current path, change:

<router-link :to="{path: 'relative/path'}" append></router-link>Copy the code

Tag renders a tag of some kind:

< the router - link to = "/ foo" tag = "li" > foo < / router - the link > < li > / / rendering results foo < / li >Copy the code

Active-class, set the CSS class name to be used when the link is activated:

<style>
 ._active{
  background-color: red;
 }
</style>
<p>
 <router-link :to="{path: '/route1'}" active-class="_active">Router Link 1</router-link>
 
 <router-link :to="{path: '/router2'}" tag="span"> Router Link 2</router-link>
</p>
Copy the code

Exact-active-class: configures the class that should be activated when the link is exactly matched

<p>
 <router-link :to="{path: '/route1'}" exact-active-class="_active">Router Link 1</router-link>
 
 <router-link :to="{path: '/router2'}" tag="span"> Router Link 2</router-link>
</p>
Copy the code

Event, a declaration that can be used to trigger navigation events:

<router-link :to="{path: '/routes1'}" event="mouseover">Router Link</router-link>
Copy the code

The transition

Effect:

Example:

<! DOCTYPE HTML > < HTML > <head> <meta charset=" UTF-8 "> <title> Transition </title> <script SRC = "https://cdn.jsdelivr.net/npm/vue/dist/vue.js" > < / script > < style type = "text/CSS" > / * * / set duration and animation function .fade-enter-active, .fade-leave-active { transition: opacity 2s; } .fade-enter, .fade-leave-to { opacity: 0; } </style> </head> <body> <div id="app"> <button @click="show=! < p style = "padding-bottom: 0px; padding-bottom: 0px; <transition name="fade"> <p V-show ="show" :style="styleobj"> </p> </transition> </div> <script> var vm = new Vue({ el: '#app', data: { show: true, styleobj: {fontSize: '30px', color: 'red'} }, computed: { }, methods: { }, watch: {} }) </script> </body> </html>Copy the code

Vue provides six switches between element show and hide transitions:

  1. v-enterDefine the state at the beginning of the transition
  2. v-enter-active, define the state when the transition takes effect
  3. v-enter-toDefine the end state of the transition
  4. v-leave, define the initial state leaving the transition
  5. v-leave-active, defines the state when the exit transition takes effect
  6. v-leave-toDefine the end state of leaving the transition

Axios

Axios is an HTTP library based on promises.

Installation:

NPM install AXIos or bower install AXIos or YARN add AXIosCopy the code

The GET method

new Vue({ el: '#app', data(){ return { info: null } }, Mounted () {axios.get(' https://domain/json_demo.json '). Then (response => (this.info = response.data)). Catch ((error) => {axios.get(' https://domain/json_demo.json '). console.log(error); }); }})Copy the code

Pass parameters:

// add the argument axios.get('/user? ID=123') .then((response)=>{console.log(response); }) .catch((error)=>{console.log(error); }); // params sets the parameter axios.get('/user', {params: {ID: 123}}). Then ((response)=>{console.log(response); }) .catch((error)=>{console.log(error); });Copy the code

The POST method, which passes data to the server

Axios.post ('https:// domain name/demo_axiOS_post.php ').then(response=>(this.info=response)).catch((error)=>{console.log(error); }) // pass axios.post('/user',{name: 'jeskson- Nezha ', password: 123 }) .then(response=>(this.info=response)) .catch((error)=>{console.log(error); })Copy the code

Execute multiple concurrent requests

function getUserAccount(){ return axios.get('/user/123'); } function getUserPermissions(){ return axios.get('/user/123/permissions'); } axios.all([getUserAccount(),getUserPermissions()]).then(axios.spread(function(acct, perms){// Both requests are now executed}));Copy the code

axios api

Axios (config) // Send the POST request axios({method: 'POST ', url: '/user/123', data: {name:' Nezha ', age: 12}}); // GET request axios({method: 'GET ', url: 'https://xxx', responseType: 'stream' }) .then(function(response){ response.data.pipe(fs.createWriteStream('xxx.jpg')) }); Axios (url[,config]) // Send the get request axios('/user/123');Copy the code

Alias of the request method

axios.request(config)
axios.get(url[,config])
axios.delete(url[,config])
axios.head(url[,config])
axios.post(url[,data[,config]])
axios.put(url[,data[,config]])
axios.patch(url[,data[, config])
Copy the code

concurrent

axios.all(iterable)
axios.spread(callback)
Copy the code

Response of the structure

The response to the AXIos request contains a lot of information:

{// data is the response provided by the server data: {}, // status is the HTTP status code status: 200, // statusText Is the HTTP status information from the server response statusText: "OK", //headers is the server response headers: {}, // config is the configuration information for the request config: {}}Copy the code

Interceptor: Intercepts requests or responses before they are processed by THEN or catch.

/ / add request interceptor axios. Interceptors. Request. Use (function (config) {/ / what to do before sending a request return config. }, funtion(error) {// What to do about the request error return promise.reject (error); }); / / add the response interceptor axios. Interceptors. Response. Use (function (response) {/ / do something to return the response to the response data; }, function(error) {return promise.reject (error); }); / / remove var myInterceptor interceptor = axios. Interceptors. Request. Use (function () {... }); axios.interceptors.request.eject(myInterceptor); Var instance = axios.create(); instance.interceptors.request.use(function () {... });Copy the code

Error handling, for example:

Axios.get ('/user/12345'). Catch (function (error) {if (error. Response) { But the status code of the server response is not in the 2xx range console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); }else{ console.log('Error', error.message); } console.log(error.config); });Copy the code

Vue Mall development

Mall module: home page, users, products, news, shopping, order processing, etc. (Picture rotation, boutique recommendation, user registration and login, product details, address management, complete shopping process, commodity join, edit, delete, batch selection, harvest address, order and member center – order, collection, footprint, address, feedback)

Home page

The homepage development

  1. Picture rotation, used to receive advertising.
  2. The realization of shortcut menu and the judgment of user login.
  3. Latest information acquisition and implementation.
  4. The latest product to hit the shelves
  5. Boutique recommended products
  • How to realize picture rotation, picture object array (click the link address of picture, picture description, picture address).
  • Local shortcut menu, generally including: latest products, activity list, help center, user center (user center to determine whether the user login, if there is a login to jump to the user center, if not to jump to the login page), user login data can be saved inlocalStorageIn the.
  • Get the latest information, loop displays the latest information list. (The latest shelves, boutique recommended the same)

User management

About the user, such as user registration, login, exit, user information modification, user password modification, user collection management, user address management and so on.

Registration:

To determine whether the login page, if you log in to the home page, if not into the home page, there are registered button in the first to the login page, the registration process, determine the user’s input information, if the information is not wrong, the interface through registration registration data, if the information is incorrect, judging on the front end, input and then judge, don’t submit to the back-end judgment.

Mobile phone registration, pay attention to avoid trouble, use the picture verification code, each time to send to obtain the verification code, fill in the picture verification code to determine the correct before sending to obtain the verification code interface. The interface displays a message indicating that the registration is successful, and the login page is automatically displayed (avoiding unnecessary operations).

The user login

Judge whether the user input the user name and password, it is best to have a prompt, submit data to the interface to judge whether there is any error, error to fill in (user name, password).

Member home Page (My page)

At the top of the user information (picture, user name, grade or level, the mobile phone number), my order menu (my order – all order, wait for payment, to send the goods, for the goods, for evaluation, these should be clear to the user see) and other features (my collection, address management, user information, password changes, log out)

Some mall software can display the necessary page, enter the member home page, judge whether to log in, such as the user is in the login state, do not do the operation, if not in the login state, in order to prevent wrong operations can be pop-up prompt, jump to the user login page or pop-up prompt to enter the user name and password, see the demand.

User exit

If the user wants to log out, he can click log out and clear the corresponding cache to realize the log out function and automatically jump to the home page.

Modifying User Information

You can change my profile picture, change my name, change my gender, change my email, etc.

Changing user Passwords

Password change display: old password (please enter the old password), new password (please enter the new password), confirm password (please enter the new password again). Of course you said forget the original password, there is a forget password function to modify the password interface, commonly used mobile phone verification code to directly modify the password.

User Address Management

Add address (display) : consignee (please enter consignee), mobile phone number (please enter mobile phone number), address, detailed address (please enter detailed address), set as the default function, you can delete the added address.

Implement the product list

  • Product classification, Product list, Product Introduction, Product details, product reviews, information list, information details
  • Read the classification of all products through the interface. After selecting the classification, read the product list according to the classification ID
  • All products are read by default for query and sorting
  • According to the selected product ID, the interface reads and displays the product introduction information
  • According to the selected product ID, the detailed information of the product is read through the interface and displayed
  • According to the selected product ID, the list of product reviews can be read through the interface. Users can only initiate reviews after purchasing products and confirming receipt
  • News list, according to the interface, read all information list
  • News details, according to the selected information Id, read the information details through the interface

At the bottom of the menu

Contents: home page, category, shopping cart, membership.

At the bottom of the product shopping details are: Home page, favorites, shopping cart, add to shopping cart, buy now (some functions need to realize different codes according to the user’s login state, the login state is normal, there is no login prompt to log in)

Shopping-order module process

Realization includes: shopping cart realization, increase or decrease the quantity of goods in shopping cart, single billing, full billing, to settle accounts, order, order list, cancel orders, to pay, confirm receipt, product comments and so on.

  • Shopping cart module, shopping cart product list, increase quantity, reduce quantity, radio billing, all billing, to settle.
  • Order, have access to the order content, select the user address, order into the box and so on.
  • Cancel the order to achieve the cancellation of the order.
  • To pay, order payment simulation implementation. (Work to achieve wechat payment function, Alipay payment function)
  • Confirm receipt of goods.
  • Implement product reviews.

Place the order page

Order page (display) : receiving address, order product list information, delivery method, freight display, message (please input message content), total amount (display amount), order payment function button, etc.

The order list

Order list (display) : to be paid, to be shipped, to be received, to be reviewed, all. Order (order number display, status, product information, quantity, total amount, function button status – Cancel order, go to pay, confirm receipt)

Product reviews

I will go to evaluate, confirm receipt of goods, product review page (display), product evaluation (asterisk display effect), message box (does the product meet your expectations? Share your experience with them), upload pictures to show, anonymous comments, etc. Click the comment function.

Go back to my previous articles and you may get more!

  • A qualified junior front-end engineer needs to master module notes
  • Vue.js pen test questions Solve common business problems
  • [Primary] Personally share notes of Vue front-end development tutorial
  • A long summary of JavaScript to consolidate the front end foundation
  • ES6 comprehensive summary
  • Dada front-end personal Web share 92 JavaScript interview questions with additional answers
  • [Illustrated, like collection oh!] Re-study to reinforce your Vuejs knowledge
  • 【 Mind Mapping 】 Front-end development – consolidate your JavaScript knowledge
  • 14 – even liver 7 nights, summed up the computer network knowledge point! (66 items in total)
  • This was my first JavaScript primer
  • LocalStorage and sessionStorage localStorage
  • Drag and drop in HTML5
  • Challenge the front-end HTTP/ECMAScript
  • Must learn must learn – Audio and video
  • 170 Interview questions + answer Learn to organize (conscience making)
  • Front-end HTML5 interviewers and candidates ask and answer questions
  • Ne Zha is sweeping the sea
  • Tencent location service development applications
  • [Advanced] The interviewer asked me how Chrome renders (6000 words)
  • The interviewer started by asking me about Chrome’s underlying principles and HTTP protocol (swastika)
  • Staying up late summed up the “HTML5 Canvas”
  • This /call/apply/bind
  • The HTTP/HTTPS/HTTP2 / DNS/TCP/classic problem
  • Execute context/scope chain/closure/first-class citizen
  • Web page creation basics
  • Learn the summary of HTML5 finger front-end (suggested collection, illustrated)

❤️ follow + like + favorites + comments + forward ❤️, original is not easy, encourage the author to create better articles

Likes, favorites and comments

I’m Jeskson, thanks for your talent: likes, favorites and comments, and we’ll see you next time! ☞ Thank you for learning with me.

See you next time!

This article is constantly updated. You can search “Programmer Doraemon” on wechat to read it for the first time, and reply [information] there are materials of first-line big factories prepared by me, which have been included in this article www.dadaqianduan.cn/#/

Star: github.com/webVueBlog/…

This article is participating in the “Nuggets 2021 Spring Recruitment Campaign”, click to see the details of the campaign