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
Don’t be afraid to dream, but don’t just dream. Be a doer, not a talker.
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 ❤ ️ ~
As a Vue developer, you must understand its usage rules.
The development of Vue. Js
The industry of front-end development is very fast, and most learners can’t keep up with the speed of development. They are learning AngularJS from Google, ReactJS from Fackbook every day. These front-end MVC (MVVM) frameworks and componentized learning, plus the emergence of vue.js, more and more front-end are involved in learning. ❤ ️
Vue.js is a front-end library for developing Web interfaces. It is lightweight, responsive programming and componentized.
hello world
The introduction of vue. Js
<script SRC ="http://cdnjs.xxx"></script> // Use the CDN methodCopy the code
Install via NPM:
npm install vue
Copy the code
Example:
<div id="#app"> <h1>{{message}}</h1> </div> var vm = new Vue({ el: '#app', data: { message: 'Hello world, I am The Gold Nuggets, Nezha'}})Copy the code
Features: Data binding
In the browser console vm.message=’hello vue’, output hello vue, indicating that vm.message is bound to the view {{message}}.
Bind data entered by the user and the view changes with the user’s input ❤️
<div id="app">
<h1>dadaqianduan is {{message}}</h1>
<input type="text" v-model="message">
</div>
Copy the code
The value of vm.message changes as the user enters the value in the input, without having to manually retrieve the DOM element value and synchronize it to JS.
Features: componentized
You can define your own HTML tags and use them in templates
Example:
<div id="app">
<message content="dadaqianduan"></message>
</div>
<script type="text/javascript">
var Message = Vue.extend({
props: ['content'],
template: '<h1>{{content}}</h1>'
})
Vue.component('message', Message);
var vm = new Vue({
el: '#app',
})
</script>
Copy the code
Command line tools:
$npm install --global vue-cli
$vue init webpack my-project
$cd my-project
$npm install
$npm run dev
Copy the code
Vue instance
The use of vue.js is to create an instance of vue using the constructor vue ({option}) : var vm = new vue ({}).
A Vue instance is equivalent to a ViewModel in MVVM mode, as shown below:
At instantiation time, you can pass in an option object (data, template, mount element, method, lifecycle hook), etc.
The template
The EL type is a string, A DOM element, or a function that provides a mount element for the instance. Typically we use CSS selectors, or native DOM elements.
For example: el:’#app’, if el is specified, the instance will be compiled immediately.
Template is a string. By default, the mount element is replaced by the template value and the element corresponding to the el value, combining the attributes of the mount element and the template root node.
data
Data can be defined in a VUE instance through the data property, which can be bound and used in the template corresponding to the instance.
Example:
var data = {a:1}
var vm = new Vue({
data: data
})
vm.$data === data // true
vm.a === data.a // true
vm.a = 2
data.a // 2
data.a = 3
vm.a // 3
Copy the code
Using {{a}} in a template will output the value of vm.a, modify the value of vM. a, the value in the template will change, called reactive data.
Instances of component types can get data from props, which, like data, needs to be preset at initialization.
<my-component title="myTitle" content="myContent"></my-component>
var myComponent = Vue.component("my-component",{
props: ['title','content'],
template: '<h1>{{title}}</h1><p>{{content}}</p>'
})
Copy the code
methods
Define a method in a methods object, for example:
<button v-on:click="daBtn">dadaqianduan</button> new Vue({ el: '#app', data: {a:1}, methods: { daBtn: function(){ console.log(this.a); }}});Copy the code
The life cycle
BeforeCreate, which is called synchronously when the instance starts initialization, before data observations, events, and so on are initialized.
Created is called after the instance is created, when the data binding and event methods are complete, but DOM compilation has not started, i.e. the document has not been mounted.
BeforeMount, run before Mounted.
Mounted, when all instructions have taken effect and the DOM update is triggered. $el is not guaranteed to be inserted into the document.
BeforeDestroy, called when instance destruction begins.
Destroyed, called after the instance is destroyed. All binding and instance directives are unbound and the subinstance is destroyed.
Updated, invoked after the instance is mounted to update the instance again and update the DOM structure.
Activated is used together with the keep-live attribute of the dynamic component. This method is invoked during the initial rendering of the dynamic component.
Text interpolation
The basic form of data binding is text interpolation, using {{}}, with Mustache syntax:
<span>hello {{name}}</span>
Copy the code
Single interpolation:
<span v-once>{{name}}</span>
Copy the code
HTML attributes
Example:
<div v-bind:id="'id-'+id"/></div>
<div :id="'id-'+id"></div>
Copy the code
Binding expression
The text you put inside the Mustache tag is called a binding expression. Only one expression can be contained in each binding. JavaScript statements and regular expressions are not supported.
The filter
Vue allow add optional filter after expression, to pipeline operators “|” instructions, there can be multiple filter chain using:
{{time | paramsTime}}
Copy the code
Calculate attribute
Var vm = new Vue({el: '#app', data: {firstName: 'da', lastName: 'nE Zha ',} computed: {fullName: Return this.firstName + "+ this.lastName}}); <p>{{firstName}}</p><p>{{lastName}}</p><p>{{fullName}}</p>Copy the code
Setter
Example:
var vm = new Vue({ el: '#el', data: { num: 100, } computed: { price: { set: function(newValue){ this.num = newValue * 100; }, get: function() { return (this.num/100).toFixed(2); }}}});Copy the code
The form controls
Example input fields:
<input type="text" v-model="message"/>
<span>dadaqianduan {{message}}</span>
Copy the code
Example of a single box:
<label><input type="radio" value="male" V-model ="gender"> male </label> <label><input type="radio" value="famale" V - model = "gender" > women < / label > < p > {{gender}} < / p >Copy the code
Checkbox checkbox, single checkbox and multiple check boxes
<input type="checkbox" v-model="checked"/>
<span>dadaqianduan{{checked}}</span>
Copy the code
Multiple checkboxes, v-model uses the same attribute name, and the attribute is array:
<label><input type="checkbox" value="1" v-model="multiChecked">1</lable>
<label><input type="checkbox" value="2" v-model="multiChecked">2</lable>
<label><input type="checkbox" value="3" v-model="multiChecked">3</lable>
<p>{{multiChecked.join('|')}}</p>
Copy the code
select
:
Radio:
<select v-model="selected">
<option selected>A</option>
<option>B</option>
<option>C</option>
</select>
<span>dadaqianduan: {{selected}}</span>
Copy the code
Pops:
<select v-model="multiSelected" multiple>
<option selected>A</option>
<option>B</option>
<option>C</option>
</select>
<span>dadaqianduan: {{multiSelected.join('|')}}</span>
Copy the code
Bind a value
The values of form controls can also be bound to dynamic properties of vUE instances.
// checkbox
<input type="checkbox" v-model="checked" v-bind:true-value="a" v-bind:false-value="b">
Copy the code
Checked: vm.checked==vm.a Unchecked: vm.hchecked==vm.bCopy the code
Class is bound to style
Class property, binding data can be objects and arrays
<div class="da" v-bind:class="{'active':active, 'unactive':! Active}"></div> The vm instance needs to contain: data: {active: true}Copy the code
Array syntax
<div v-bind:class="[classA, classB]"></div>
data: {
classA: 'class-a',
classB: 'class-b',
}
Copy the code
<div class=”class-a class-b “>
Inline style binding
- Object syntax: Directly bind objects that conform to the style format
<div v-bind:style="dada"></div>
data: {
dada: {
color: 'green',
fontSize: '10px'
}
}
Copy the code
<div v-bind:style="{ fontSize: color: 'green' }"></div>
Copy the code
- Array syntax:
v-bind:style
Allows multiple style objects to be bound to a unified element.
<div v-bind:style="[ styleObjectA, styleObjectB ]"></div>
Copy the code
Template rendering
Advantages of front-end rendering:
First, business separation, back-end only need to provide interface, front-end development does not need to deploy to the due back-end environment, through some proxy server tools can be remote access to back-end data for development, can improve the development efficiency.
Second, the amount of calculation has to be transferred, the original back-end rendering task is handed over to the front-end, reducing the server pressure.
Advantages of back-end rendering:
First, search engine friendly.
Second, the loading time end of the home page, the back-end rendering will directly display HTML after loading, but the front-end rendering still needs a period of JS rendering time after loading.
Conditions apply colours to a drawing
V-if and V-else are used to determine whether to print the DOM element and its child elements based on the data values.
V-else must be followed by V-if, otherwise this instruction will not work.
The use of v-show elements is rendered and stored in the DOM. Just toggle the element’s CSS property display.
When v-IF and V-show conditions change, V-if causes a change in the level of DOM manipulation, whereas V-show only changes in style. From a switching point of view, V-show consumes less performance than V-IF.
When v-if switches, vue.js has a partial compile/uninstall process, because templates in V-if may also include data bindings or subcomponents. The V-if ensures that the conditional block is properly destroyed with in-between event listeners and subcomponents during the switch.
V-if is lazy. If the initial condition is false, v-if itself does nothing, whereas v-show still does everything normal, and then sets the CSS style to display: None.
V-if has a higher switching cost and V-show has a higher initial rendering cost
The list of rendering
Example:
< ul > < li v - for = "item in the items" > < h3 > {{item. Web}} < / h3 > < p > {{item. Da}} < / p > < / li > < / ul > var = new vm Vue ({el: '#app', data: {items: [{title: 'web-1', description: 'da-1'}, {title: 'web-2', description: 'da - 2}, {title:' web - 3 'description:' da - 3}, {title: 'web - 4' description: 'da - 4'}}});Copy the code
V-for has a built-in $index variable, which prints the index of the current array element. You can also specify the alias of the index. < li v – for = “(index, item) in the items” > {{index}} – {{$index}} – {{item. The title}} < / li >
The $set method is provided in vue.js to modify data while attempting to update it.
vm.$set('item[0]', {title: 'da'})
Copy the code
The modifier
.stop: equivalent to calling event.stopPropagation ().
.prevent: Equivalent to calling event.preventDefault().
.capture: Use capture mode to add event listeners. .self: The callback is triggered only if the event is triggered from the listening element itself.
Example:
<form V-on :submit. Prevent ="onSubmit"></form> // Prevent ="onSubmit"></form> // Prevent the default submission event and prevent bubbling <form V-on :submit.stop.prevent></form> // Can also have modifiers only and no events boundCopy the code
Vue.extend()
Vue.js provides vue.extend (options) methods that create “subclasses” of the base Vue constructor
Vue.component('child', child) // Global register child... Var child = vue.extend ({template: '#child', data: function() {return {... var child = vue.extend ({template: '#child', data: function() {return {... .}}... .})Copy the code
Built-in commands
V-bind is used to dynamically bind the DOM element attribute, whose actual value is provided by the DATA attribute in the VM instance.
<img v-bind:src="avatar"/>
new Vue({
data: {
avatar: 'http://'
}
})
Copy the code
V-text needs to be bound to an element to avoid flash problems before compilation.
V-ref acts on child components, which instances can access via $refs.
Example:
<message v-re:title content="title"></message>
<message v-ref:sub-title content="subTitle"></message>
var Message = Vue.extend({
props: ['content'],
template: '<h1>{{content}}</h1>'
});
Vue.component('message', Message);
Copy the code
The v-pre instruction skips compilation of this element and child elements and displays the original {{}}Mustache tag, which is used to reduce compilation time.
The v-clock directive is equivalent to adding a [V-cloak] property to the element until the associated instance finishes compiling. You can use it with the CSS rule [V-cloak]{display: None} to hide uncompiled Mustache tags until the instance is ready.
<div v-cloak>{{msg}}</div>
Copy the code
The V-once directive is used to indicate that an element or component is rendered only once, and that the element or component and its children will not be compiled or rendered again, even if the binding data is subsequently changed or updated.
Custom instruction
Register a global custom directive with the vue.directive (id,definition) method, which takes the id and defines the object. The ID is the unique identifier of the directive, and the definition object is the related properties and hook functions of the directive.
Vue.directive('global-directive', definition)
<div v-global-directive></div>
Copy the code
Local registration:
var com = Vue.extend({
directives: {
'localDirective': {}
}
});
Copy the code
Instruction instance attribute
el
The element bound by the directivevm
, the context of the instructionViewModel
fornew Vue()
Can also be a component instance.expression
, the expression of the instruction, excluding arguments and filtersarg
, the parameter of the instructionname
, the name of the instructionmodifiers
, an object that contains a modifier for an instructiondescriptor
, an object that contains the parse result of an instruction
The filter
Vue.js can add an optional filter after an expression, represented by a pipe character:
{{time | paramsTime }}
Copy the code
The essence of a filter is a function that accepts the value preceding the pipe as its initial value, and can also accept additional arguments and return the processed output value.
Vue.filter('date', function(value){ if(! value instanceof Date) return value; return value.toLocalDateString(); }) </div> {{ date | date }} </div> var vm = new Vue({ el: '#app', data: { date: new Date() } })Copy the code
The component registration
Example:
var MyComponent = Vue.extend({... })Copy the code
Vue. js provides two registration methods, global registration and local registration respectively.
Vue.component('my-component', MyComponent);
Copy the code
Usage:
<div id="app"> <my-component></my-component> </div> var MyComponent = Vue.extend({ template : Vue.component('my-component', MyComponent) var vm = new Vue({el: '#app'});Copy the code
Local registration
var Child = Vue.extend({ template : '<p>dadaqianduan.cn</p>' }); Var Parent = vue.extend ({template: '<div> <p>dada</p> <my-child></my-child> </div>', components: var Parent = vue.extend ({template: '<div> <p>dada</p> <my-child></ div>', components: {'my-child': child}});Copy the code
Register grammar sugar
Example:
Vue.component('my-component', {template: '<p>dadaqianduan.cn</p>'}) var Parent = vue.extend ({template: '<div> <p> <my-child></my-child> </div>', components: {'my-child': {template: '< p > dada < / p >'}}});Copy the code
componentprops
Props passes data from the parent component to the child component, and when the child component accepts the data, it needs to declare props.
Example:
Vue.component('my-child', { props : ['parent'], template: '<p>{{parent}} is from parent'}) <my-child parent=" "></my-child>Copy the code
Prop: Number, accept the parameters for the primary constructor, String, Number, Boolean, Function, Object, Array, also can accept null, means that any type.
Multiple types: prop: [Number,String],; Parameter required: prop:{type: Number, required: true}.
Parameter default: prop: {type: Number, default: 12},
Example:
prop: {
type: Object,
default: function() {
return {a: 'a'}
}
}
Copy the code
Intercomponent communication
Vue.js provides three properties for direct access to its parent component and root instance.
$parent
, parent component instance$children
Contains all child component instances$root
, the root instance of the component
It is recommended that props be used to pass data between components.
$emit
Example:
'add' : function(MSG) {this.todo.push(MSG); }} methods: {onClick: function() {this.$emit('add', 'dada'); }}Copy the code
$dispatch
Example:
'add' : function(MSG) {this.todo.push(MSG); Function () {this.$dispatch('add', 'dada'); }}Copy the code
Subcomponent index
Vue.js provides direct access to child components, binding them with a V-ref directive in addition to this.children.
<child-todo v-ref:first></child-todo>
Copy the code
The child component instance can be retrieved from the parent component by this.$refs.first.
Component caching
Keep-alive can preserve its state or avoid re-rendering if it keeps the switched out component in memory.
<keep-alive>
<component :id="currentView">
</component>
</keep-alive>
Copy the code
Life cycle:
BeforeCreate (){console.log(" before components are created ")} created(){console.log(" after components are created ")} beforeMount(){console.log(" after components are created ")} beforeMount(){ Console. log(" before components are rendered ")} mounted(){console.log(" after components are rendered ")} beforeUpdate(){console.log(" before components are rendered ")} updated() {console.log(" before components are rendered ")} updated() {console.log(" before components are rendered ")} Console. log(" Data changes after rendering} beforeDestory(){// Before component destruction} deStoryed (){// After destruction}Copy the code
Custom instructions and filters
{focus: function(el){// Focus element el.focus()}})Copy the code
Register local directives. The component also accepts a CACHE option:
Inserted: function(el){el.focus(); }}}Copy the code
The filter
Vue.js filters can be used in two places: double curly brace interpolation and V-bind expressions.
{{message | capitalize}}
<div v-bind:id="rawId | formatId"></div>
Copy the code
Local filters can be defined in a component’s options:
filters: {
capitalize: function(value) {
if(!value) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1);
}
}
Copy the code
Vue.filter("author",function(value){
return value+"-dadaqianduan";
})
Vue.filter("money", function(value){
return "$"+value;
})
Copy the code
Axios base GET request
Axios is a Promise-based HTTP library that can be used in browsers and Node.js.
Features:
- Created from the browser
XMLHttpRequests
- from
node.js
createhttp
request - support
Promise api
- Intercept requests and responses
- Transform request data and response data
- Cancel the request
- Automatic conversion
JSON
data - The client supports defense
XSRF
Installation:
Use NPM:
npm install axios
Copy the code
Execute the GET request:
axios.get('/user? ID=123') .then(function(response){ console.log(response); }) .catch(function(error){ console.log(error); }); axios.get('/user', { paras: { ID: 123 } }) .then(function(response){ console.log(response); }) .catch(function(error){ console.log(error); });Copy the code
Performing a POST request
axios.post('/user', {
firstName: 'da',
lastName: 'jeskson'
})
.then(function(response){
console.log(response);
})
.catch(function(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){
}));
Copy the code
Axios API: Requests can be created by passing configuration to AXIos
// axios(config) axios({method: 'post', url: '/user/123', data: {firstName: 'dada', lastName: 'dadaqianduan'}});Copy the code
axios(url[,config])
// Send the get request axios('/user/123');Copy the code
Example:
created(){ this.$axios.get("http://xxx") .then(res=>{ this.axiosData = res.data }) .catch(error => { console.log(error); }}})Copy the code
vue-axios
Global configuration and interceptors
The global AXIos default value:
axios.defaults.baseURL='http://xxx';
Copy the code
Default value for custom instance:
Var instance = axios.create({baseURL: 'http://xxx'});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) {/ / do something before sending a request return config}, function (error) {/ / the request do wrong 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(errror){return promise.reject (error); });Copy the code
Add a request interceptor
Axios. Interceptors. Request. Use (function (config) {/ / do something before sending a request if (config. The method = = = 'post') {config. Data = qs.stringify(config.data); } console.log(config); return config; },function(error){return promise.reject (error); });Copy the code
vue-axios
Cross domain processing
Proxy: {host: '127.0.0.1', port: 9000, auth: {username: 'jeskson', password: '123'}}Copy the code
Routing based
<div id="app">
<router-view></router-view>
</div>
const User = {
template: '<div>User</div>`
}
const router = new VueRouter({
routes: {
{path: '/user/:id', component: User}
}
})
Copy the code
router-link
The
component allows users to navigate through applications with routing functions. The to attribute specifies the destination address, which is rendered as a
tag with the correct link by default. You can configure the tag attribute to generate other tags. In addition, when the destination route is successfully activated, the link element automatically sets a CSS class name to indicate that the route is activated.
instead of writing
would be better.
- Whether it is
html5 history
Mode orhash
Mode, it behaves consistently, so when you switch routing modes, or inie9
degradehash
Mode without any changes. - in
html5 history
Mode,router-link
Will guard the click event so that the browser does not reload the page. - When you are in
html5 history
Use in modebase
After the choices, all of themto
Properties don’t need to write base paths anymore.
Nested routing
To render components in nested exits, use the children configuration in the parameters of the VueRouter:
const router = new VueRouter({
routes: [
{path: '/user/:id', component:User,
children: [
{
path: 'profile',
component: UserProfile
},
{
path: 'posts',
components: UserPosts
}
]
})
Copy the code
Routing parameter transmission:
<router-link :to="{name: 'dada', params: {id:'111', count: 12}}">Copy the code
Vue framework comparison
vue:
- Flexible selection of templates and rendering functions
- Simple syntax and project creation
- Faster rendering speed and smaller size
react:
- More suitable for large applications and better testability
- It is suitable for both web and native APPS
- A larger ecosystem brings more support and tools
Vue core idea
Data driven and componentization
Nodejs and NPM installation and environment setup
Webpack
Code modularization builds the packaging toolGulp
A flow-based automated build toolGrunt
isJavaScript
World building toolsBabel
Is written using the latest specificationjs
vue
It’s built data drivenweb
A progressive framework for interfacesExpress
Is based onNode.js
Platform, fast, open, minimalistweb
Development framework
Download: nodejs.org/en/download…
Vue environment construction and VUE-CLI use
Vue multi-page application file references:
<script src="https://unpkg.com/vue/dist/vue.js"></script>
Vue-cli build spa application
npm install -g vue-cli
vue init webpack-simple demo
vue init webpack demo2
Copy the code
a vue.js project
npm install
npm run dev
npm run build
Copy the code
Vue basic syntax
Mustache syntax: {{MSG}}
html
Assignment:v-html=""
- Binding properties:
v-bind:id=""
- Use expressions:
{{ok? 'yes':'no'}}
- Text assignment:
v-text=""
- instruction
v-if=""
- Filter:
{{message | capitalize}}
Class and style binding
- Object syntax:
v-bind:class="{active: isActive, 'text-danger': hasError}">
- Array syntax:
<div v-bind:class="[activeClass,errorClass]">
style
Binding object syntax:v-bind:style="{color:activeColor,fontSize:fontSize+'px'}"
Vue components
- Global components and local components
- Parent – child component communication – data transfer
- Slot
Vue-router
What is front-end routing: displaying different content or pages based on different URLS
Vue-router is used to build the SPA
<router-link></router-link> or this.$router-push ({path:''}) <router-view></router-view>Copy the code
- Dynamic Route Matching
- Embedded routines by
- Programmatic routing
- Named routes and named views
What is dynamic route matching
Example:
import GoodsList from './.. /views/GoodsList' Vue.use(Router) export default new Router({ routers: [ { path: '/goods/:goodsId', name: 'GoodsList', component: GoodsList } ] }) <template> <div> <span>{{$route.params.goodsId}}</span> </div> </template>Copy the code
What is nesting by
// App.vue
<template>
<div id="app">
<img src="./assets/logo.png">
<router-view></router-view>
</div>
</template>
Copy the code
import GoodsList from './.. /views/GoodsList' import Title from '@/views/Title' import Image from '@/views/Image' Vue.use(Router) export default new Router({routers: [{path: '/goods', name: 'GoodsList', Component: 'GoodsList', children: [{path: 'title', name: 'title', component: Title }, { path: 'img', name: 'img', component: Image } ] } ] }) <template> <div> <span>{{$route.params.goodsId}}</span> <router-link To ="/goods/title"> </router-link> </router-link> <router-view></router-view> </div> </div> </template>Copy the code
What is programmatic routing
Through JS to achieve the page jump.
$router.push("name") $router.push({path:"name"}) $router.push({path:"name? A = 123 "}) or $router. Push ({path: "name", query: {a: 123}}) $router. Go (1)Copy the code
import GoodsList from './.. /views/GoodsList' import Title from '@/views/Title' import Image from '@/views/Image' import Cart from '@/views/Cart' Vue.use(Router) export default new Router({ routers: [ { path: '/goods', name: 'GoodsList', component: GoodsList, children: [{path: 'title', name: 'title', Component: title}, {path: 'img', name: 'img', component: Image } ] }, { path: '/cart', component: Cart}]}) <template> <div> <span>{{$route.params.goodsId}}</span> <router-link to="/goods/title"> <router-link to="/goods/image"> </router-link> <div> <router-view></router-view> </div> <router-link To = "/ cart" > shopping cart < / router - the link > < button @ click = "jump" > jump shopping cart < / button > < / div > < / template >... methods: { jump() { this.$router.push("/cart"); // ({path: '/cart? id=123'}); }}Copy the code
Command routing and named views
Define different names for routes and match routes based on the names
Define names for different router-views and render corresponding components by their names
<router-link v-bind:to="{name: 'cart'}"> Jump to the cart page </router-link> <router-link V-bind :to="{name: </router-link> Route :{path: '/cart/:cartId ', name: 'cart', Component :cart}Copy the code
The code for app.vue is as follows:
<template>
<div id="app">
<img src="./assets/logo.png">
<router-view></router-view>
<router-view name="title"></router-view>
<router-view name="img"></router-view>
</div>
</template>
Copy the code
router/index.js
import Vue from 'vue' import Router from 'vue-router' import GoodsList from './.. /views/GoodsList' import Title from '@/views/Title' import Image from '@/views/Image' import Cart from '@/views/Cart' Vue.use(Router); export default new Router({ routers: { { path: '/', name: 'GoodsList', components: { default: GoodsList, title: Title, img: Image } }, { path: '/cart/:cartId', name: 'cart', components: Cart } } })Copy the code
Vue – resource and Axios
Download and install:
< script SRC = "https://cdn.jsdelivr.net/vue.resource/1.3.1/vue-resource.min.js" > < / script > NPM install vue ressource - saveCopy the code
Vue-resource’s request API is designed in the REST style and provides seven request apis:
get(url, [options])
head(url, [options])
delete(url, [options])
jsonp(url, [options])
post(url, [body], [options])
put(url, [body], [options])
patch(url, [body], [option])
Copy the code
Global interceptors
Vue. HTTP. Interceptors. Push {(request, next) = > {/ / before the request processing logic next ((response) = > {/ / after the request processing logic return response})})Copy the code
Vue-resource-.html (Global interceptor)
mounted() {
Vue.http.interceptors.push(function(request,next){
next(function(response){
return response;
});
});
}
Copy the code
The use of axios
<script src="https://unpkg.com/axios/dist/aios.min.js"></script>
npm install axios -save
Copy the code
Example:
function getUserAccount(){
return axios.get('/user/12345');
}
function getUserPermissions(){
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function(acct, perms){
}));
Copy the code
mounted: function(){ axios.interceptors.request.use(function(config){ return config; }) axios.interceptors.response.use(function(response){ return response; })}Copy the code
Common ES6 commands
Rest arguments and extensions to functions, use of Promise, use of module.exports and ES6 import/export
let checkLogin = function () { return new Promise(function(resolve,reject){ let flag = document.cookie.indexOf("userId") > 1? true:false if(flag) { resolve({ status: 0, result: true }) }else{ reject("error"); }})}; checkLogin().then(function(res){ if(res.status==0){ console.log("login success"); } }).catch((error)=>{ console.log(`error:${error}`); })Copy the code
Once you have a name, you need a chunk to receive it
export let sum = (x,y)=>{ return x+y; } export let minus = (m,n) => { return m-n; } import {sum, minus} from '. / util sum () the console. The log (` sum: ${sum (1, 2)} `);Copy the code
Import * as util from './util' // util. Sum (1,2)Copy the code
AMD, CMD, CommonJS and ES6
AMD
isRequireJS
Standardized output of module definitions during the promotion processCMD
isSeaJS
Standardized output of module definitions during the promotion processCommonJS
Specification –module.exports
Example:
exports.area = function(r){
return Math.PI * r * r;
};
Copy the code
The scaffold
Vue basics: Environment setup, templates, calculated properties, classes and styles, conditions, list rendering, event handling, insight into components, Routing basics, Vuex Basics.
vue-cli@3 [email protected] // The first build NPM install -g@vue /cli // the second build YARN global add @vue/cliCopy the code
V – short for bind
<a v-bind:href="url">... <a :href="url">... </a>Copy the code
V – on abbreviation
<a v-on:click="doSomething"> <a @click="doSomething>... </a>Copy the code
Custom instruction
Declare the name of a custom directive, using the vue.directive declaration, and set the hook function to do what at what time:
Inserted: function(el){// Focus element el.focus()}})Copy the code
Hook function
An instruction definition object can provide the following hook functions:
Bind, which is called only once, when the directive is first bound to an element, where one-time initialization can be done.
Inserted, called when the bound element is inserted into a parent (the parent is guaranteed to exist, but not necessarily already inserted into the document).
Update, called when the component’s VNode is updated, but may occur before its child VNodes are updated. The value of the directive may or may not have changed, but you can ignore unnecessary template updates by comparing the values before and after the update.
ComponentUpdated, invoked when the VNode of the component where the directive resides and its child VNodes are all updated.
Unbind, called only once, when an instruction is unbound from an element.
The instruction hook function is passed the following arguments
El, the element bound by the directive, can be used to manipulate the DOM directly.
Binding, an object containing the following attributes:
-
Name, the instruction name, without the V – prefix
-
Value: specifies the binding value of the directive. For example, v-my-directive=”1+1″, the binding value is 2
-
OldValue, the previous value of the directive binding, is available only in the UPDATE and componentUpdated hooks, regardless of whether the value changes.
-
Expression: a directive expression in the form of a string. For example, in v-my-directive=”1+”, the expression is “1+1”
-
Arg, the parameter passed to the instruction, optional. For example, in v-my-directive:foo, the parameter is “foo”.
-
Modifiers – an object that contains modifiers, such as v-my-directive.foo.bar, which are {foo:true,bar:true}
-
Vnode: a virtual node generated by vUE compilation.
-
OldVnode, the previous virtual node, is only available in update and componentUpdated hooks.
All parameters except el should be read-only and do not change them. If you need to share data between hooks, it is recommended to do so through the element’s dataset.
Calculate attribute
Example:
<div id="jeskson">
<p>{{message}}</p>
<p>{{reversedMessage}}</p>
</div>
Copy the code
Application scenario: Data monitoring with dependencies.
The event
- Event definitions and abbreviations
- Event pass parameters and event objects
- Quickly combine keyboard events to improve efficiency
Event modifier
Calling event.preventDefault() or event.stopPropagation() in the event handler is a very common requirement.
Vue.js provides event modifiers for V-Ons:
.stop
.prevent
.capture
.self
.once
.passive
Copy the code
Learn more about components
Props, parameter passing of the component; Slot, the application of slot in component abstract design; Custom event, parent-child component communication.
Lifecycle hook
beforeCreate
Before component creationcreated
Before component creationbeforeMount
Components before mountingmounted
Components are mountedbeforeUpdate
Before component updateupdated
Component update completedbeforeDestory
Before component destructiondestory
Component destruction completed
Example:
<div id="app"> <h1>{{dada}}</h1> <button V-on :click="updateInfo"> </button> <button </button> </div> var vm = new Vue({el: '#app', data: {info: 'dadaqianduan.cn '}, beforeCreate: function(){console.log("beforeCreated, before component creation "); console.log(this.$el); console.log(this.$data); }, created: function(){console.log("created, component created "); console.log(this.$el); console.log(this.$data); console.log(this.$data.info); }, beforeMount: function() {console.log("beforeMounted, components before mounting "); console.log(this.$el); console.log(this.$data); console.log(this.$data.info); }, mounted: function(){console.log("mounted "); console.log(this.$el); console.log(this.$data); console.log(this.$data.info); }, beforeUpdate: function(){console.log("beforeUpdate, component beforeUpdate "); console.log(this.$el); console.log(this.$data); console.log(this.$data.info); }, updated: function(){console.log("updated, component updated "); console.log(this.$el); console.log(this.$data); console.log(this.$data.info); }, beforeDestroy: function(){console.log("beforeDestory, component beforeDestroy "); console.log(this.$el); console.log(this.$data); console.log(this.$data.info); }, destroyed: function(){console.log("destoryed, component destroyed "); console.log(this.$el); console.log(this.$data); console.log(this.$data.info); }})Copy the code
-beforecreate: before the component is created, the DOM element EL and the data for the component are not created.
el: undefined
data: undefined
Copy the code
Component created -created: The component’s data has been created, but the DOM element’s EL has not been created
El: undefined constant data: {info: 'dadaqianduan.cn '}Copy the code
Component-beforemount: THE DOM element is created without data in data
El has a value, data has a value, info has no valueCopy the code
– Mounted: Indicates that data contains a value. El,data,info all have values.
Component before update-beforeUpdate: Data data is updated, and the content of dom elements is updated synchronously.
Updated: Data is updated and the content of the DOM element is also updated.
Before component destruction -beforeDestroy: Before destruction, it is no longer managed by vUE, but data can continue to be updated, but the template is no longer updated.
Destroyed: Components are no longer managed by VUE after they are destroyed.
Life cycle stage
-
New Vue(), creates a Vue instance
-
Initialization, events, and life cycles
-
beforeCreate
-
Initialization, injection, and validation
-
created
-
$vm.$mount(el) {$vm.$mount(el) {
-
Specify template option – (yes: compile template into render function, no: compile HTML outside el as template)
-
beforeMount
-
Create vm.$el and replace el with it
-
mounted
-
Mount complete (such as when data is modified, call beforeUpdate-, enter the virtual DOM to re-render and apply the update, call updated.
-
When the vm.$destroy() function is called.
-
beforeDestroy
-
Unbind, destroy child components and event listeners
15. Destroyed
Parent-child component communication
The parent component can be passed to the child component via props, and the child component can be passed to the parent component via $parent,$emit.
Import dada from './components/ dada 'export default {name: 'App', // register components: {Dada} }Copy the code
Process: import, register, use.
props
Example:
Vue.component('da-da', { props: ['textTitle'], template: '< h2 > {{textTitle}} < / h2 >'}) / / using the < da - da text - the title = "dadaqianduan. Cn" > < / da - da >Copy the code
Prop types are as follows:
props: {
title: String,
likes: Number,
isPublished: Boolean,
commentIds: Array,
author: Object,
callback: Function,
contactsPromise: Promise
}
Copy the code
Pass static or dynamic prop
<da-da title="dadaqianduan.cn"></da-da>
Copy the code
Prop can be dynamically assigned via V-bind:
<da-da v-bind:title="dada.title"></da-da> <da-da v-bind:title="dada.title+'da da'+dada.author.name"> </da-da>Copy the code
Updates to the parent prop flow down to the child, but not the other way around. This prevents accidental changes to the parent’s state from the child, meaning that you should not change the prop inside a child, or vUE will warn you in the browser console.
This prop is used to pass an initial value; This child component next wants to use it as a local prop data. In this case, it is best to define a local data Property and use the prop as its initial value
Example:
props: ['dada'],
data: function () {
return {
counter: this.dada
}
}
Copy the code
It is passed in as a raw value and needs to be converted.
Example:
props: ['size'],
computed: {
normalizedSize: function () {
return this.size.trim().toLowerCase()
}
}
Copy the code
Prop validation
Example:
Vue.component('my-component', {props: {// Basic type checking (' null 'and' undefined 'will pass any type verification) propA: Number, // multiple possible types propB: [String, Number], // Required String propC: {type: String, required: true}, // Numbers with default values propD: {type: Number, default: 100}, // Object with default values propE: {type: Object, // Object or array default values must be obtained from a factory function default: function () {return {message: 'hello'}}}, // custom validation function propF: {validator: Function (value) {// This value must match one of the following strings: return ['success', 'warning', 'danger'].indexof (value)! == -1}}}})Copy the code
Type checking
Type can be one of the following native constructors: check with instanceof for validation.
String
Number
Boolean
Array
Object
Date
Function
Symbol
Copy the code
$emit
The child component passes communication to the parent through $emit.
$emit(eventName,[...args]) parameters: 1. {string} eventName 2. [...args] Triggers the event on the current instance and the additional parameters are passed to the listener callback.Copy the code
When $emit(eventName) is executed in the child component, the corresponding event in the parent component is emitted.
‘parent’ : ‘parent’ : ‘parent’ : ‘parent’ : ‘parent’ is an instance property of vue that represents the parent instance of the current component
If the parent component has a method called sayDa, the child component can call the parent component’s method directly with this.$parent. SayDa.
Vuex project actual combat
- Basic procedures for using Vuex
- The core concept of Vuex
- Vuex implements service functions
Vuex overview
The way data is shared between components
If the parent wants to pass a value to the child, use the V-bind attribute
If a child component wants to pass a value to its parent, use the V-ON event binding
Sharing data between sibling components: EventBus
$on
The component that receives the data$emit
The component that sends the data
What is Vuex
Vuex is a mechanism for managing global status data of components, facilitating data sharing among components.
Benefits of unified state management using VUEX
1. Centralized management of shared data in VUEX, easy to develop and maintain
2. Can efficiently realize data sharing between components and improve development efficiency
3. The data stored in VUEX is responsive and can be synchronized with the page in real time
What kind of data can be stored in VUEX
In general, only the data shared between components is stored in VUEX. For private data in components, data is stored in the components themselves.
Basic use of VUE
- Install vuEX dependency packages
npm install vuex --save
Copy the code
- Import vuex package
import Vuex from 'vuex'
Vue.use(Vuex)
Copy the code
- Creating a Store object
Const store = new vuex. store ({// state: {count:0}})Copy the code
- Mount the Store object to the Vue instance
New Vue({el: '#app', render: h=>h(app), router, render: h=>h(app), render: h=>h(app), router,Copy the code
The core concept of VUEX
The first way a component can access data in state:
This.$store.state. The global data nameCopy the code
The second way for a component to access data in state:
Import {mapState} from 'vuex'Copy the code
Use the newly imported mapState function to map the global data required by the current component to the computed properties of the current component:
// Map global data to the computed property of the current component, computed: {... mapState(['count']) }Copy the code
Mutation is used to modify store data
- Only through
mutation
changeStore
Data, cannot be operated directlyStore
Data in. - This is a slightly more cumbersome way to operate, but you can centrally monitor all data changes.
Mutations: mutations const store = new Vue. Store ({state: {count: 0}, mutations: {add(state) {count++}}})Copy the code
This.upgradesmutations () {this.upgradesmutations () {this.upgradesmutations ())}}Copy the code
Mutations can pass parameters when triggered:
Mutations const store = new vuex. store ({state: {count: 0}, mutations: AddN (state,step){// Change status state.count += step}}})Copy the code
Use this. code. store.mit ('addN',1)}}Copy the code
This. codestore.com MIT () is the first way to trigger mutations, and the second way is as follows:
MapMutations} import {mapMutations} from 'vuex'Copy the code
Map the required mutations function to the methods of the current component:
methods: { ... mapMutations(['add','addN']) }Copy the code
Do not perform an asynchronous operation in the mutations function
Action is used to process asynchronous tasks.
If the data is changed by an asynchronous operation, it must be changed through an Action rather than Mutation, but the data is changed indirectly by triggering Mutation in the Action.
Mutations: {add(state){state.count(); } }, actions: { addAsync(context){ setTimeout(()=>{ context.commit('add') },1000) } }Copy the code
// Trigger Action mothods: {handle() {this.$store. Dispatch ('addAsync'); }}Copy the code
The action asynchronous task is triggered with parameters:
this.$store.dispatch('addNAsync',5)
Copy the code
The second way to trigger actions is:
Import {mapActions} from 'vuex' import {mapActions} from 'vuex'Copy the code
Map the required Actions functions to the current component’s methods:
methods: { ... mapActions(['addAsync','addNASync']) }Copy the code
import {mapState,mapMutations,mapActions} from 'vuex computed: { ... mapState(['count']) }, methods: { ... mapMutations(['sub','subN']), ... mapActions(['subAsync']), btnHandler1(){ this.sub() }, btnHandle2(){ this.subN() } }Copy the code
getter
The getter vuex
Getters are used to process data in a Store to form new data
- Getters can process existing data in the Store to form new data.
- When the data in the Store changes, the data in the Getter changes
const store = new Vuex.store({
state: {
count: 0
},
getters: {
showNum: state => {
return state.count
}
}
})
Copy the code
The first way to use Getters is:
This $store. Getters. NameCopy the code
The second way to use getters is:
import { mapGetters } from 'vuex' computed: { ... mapGetters(['showNum']) }Copy the code
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/…