Vue.js chapter notes (detailed)

Concept of Vue.js

  • Vue.js is currently a relatively popular front-end framework, and React is a relatively popular front-end framework (in addition to developing websites, React can also develop mobile apps, and Vue syntax can also be used to develop collection apps, which requires the help of Weex)
  • Vue.js is one of the mainstream front-end frameworks, together with Angular.js and React.js, and has become the three mainstream front-end frameworks!
  • Vue.js is a framework for building user interfaces, focusing only on the view layer . It is not only easy to use, but also easy to integrate with third-party libraries or existing projects. (Vue has a supporting third-party class library, which can be integrated for the development of large-scale projects)
  • The main job of the front end? Mainly responsible for the V layer in MVC (the main job is to deal with the interface to create the effect of the front-end page)

The following is a diagram of the relationship between MVC and MVVM

insert image description here

What is the componentization idea of ​​vue.js?

  1. It provides an abstraction that allows us to develop independent and reusable widgets to construct our applications.
  2. Any application will be abstracted into a component tree.

Basic steps for registering components

  1. Create a component constructor
    and call the Vue.extend() method
  2. Register the component
    and call the Vue.component() method
  3. Using Components
    Using components within the scope of a Vue instance
<!-- 最基本的理解 -->
<div id="app">
    <my-cpn></my-cpn>
</div>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script>
    //ES6  `abc`可以换行
    //1.创建组件构造器对象
    const cpnC = Vue.extend({
        template:`
         <div>
            <h2>我是标题</h2>
            <p>我是内容</p>
            <p>我是内容,哈哈哈哈哈哈</p>
         </div>`
    })
    //2.注册组件
    Vue.component('my-cpn',cpnC)
    const app = new Vue({
        el:'#app',
        data:{
            message:'你好啊'
        },
        methods:{}
    })
</script>

Global component: means it can be used under multiple Vue instances

Local components: directly mounted under the vue instance

 const app = new Vue({
        el:'#app',
        data:{
            message:'你好啊'
        },
        methods:{},
        //2.注册组件(局部组件)
        components:{
            //cpn使用组件时的标签名
            cpn:cpnC
        }
    })

parent and child components

There is a hierarchical relationship between components
and one of the very important relationships is the relationship between parent and child componentsinsert image description here

Syntactic sugar for registering components

  • The way to register components above may be a bit cumbersome
  • In order to simplify this process, Vue provides syntactic sugar for registration
  • The main reason is that the step of calling Vue.extend() is omitted, but an object can be directly used instead.
<body>
<div id="app">
    <cpn1></cpn1>
    <cpn2></cpn2>
</div>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script>
    //1.全局组件注册的语法糖
    //1.创建组建构造器
    //const cpnC1 = Vue.extend()
    //2.注册全局组件(语法糖)
    Vue.component('cpn1',{
        template:`
        <div>
            <h2>我是标题1</h2>
            <p>我是内容,全局</p>
        </div>`
    })
    //2.注册局部组件的语法糖
    const app = new Vue({
        el:'#app',
        data:{},
        components:{
            'cpn2':{
                template:`
                    <div>
                        <h2>我是标题1</h2>
                        <p>我是内容,局部</p>
                    </div>`
            }
        }
    })
</script>
</body>

Separation of templates

  • Syntactic sugar simplifies the registration process of Vue components, and there is another place where the writing method is more troublesome, that is, the writing method of the template module.
  • If we can separate and write the html in it, and then mount it on the corresponding components, the structure will inevitably become very clear.
  • Vue provides two options to define the content of HTML modules:
    (1) use <script type="text/x-template"></script>
    (2) use <template>tags

Can components access Vue instance data

  1. A component is an encapsulation of a separate functional module (this module has its own HTML module and should also have its own data)
  2. The data in the Vue instance cannot be directly accessed in the component
  3. Vue components should have their own place to save data (the component object also has a data attribute, and can also have attributes such as methods, but the data attribute must be a function, and this function returns an object, which stores data inside)

Why component data attribute must be a function

  • If it is not a function, they will have a lot of influence on each other.

Parent components pass data (props) to child components

The value of props has two ways:

  1. An array of strings, the strings in the array are the names when passed.
  2. Object, the type of object can be set when passing, and the default value can also be set.

Child components pass data to parent components (custom events)

  1. When a child component needs to pass data to a parent component, a custom event is used.
  2. v-on can be used not only for listening to DOM events, but also for custom events between components.

The flow of custom events:

  1. In subcomponents, events are triggered through $emit().
  2. In the parent component, listen to child component events through v-on.

conditional judgment

1. v-if/v-else-if/v-else
2. The difference between v-show and v-if

  • v-show is to change the css attribute, and v-if is to determine whether the label exists or not

Access method of parent-child components: $children

  • Parent component accesses child components: use $childrenor $refsreference (reference)
  • Child components access parent components: use$parent
  • this.$childrenis an array type that contains all child component objects.
  • Here we use a traversal to take out the message status of all subcomponents

slot

  • Component slots: to make our packaged components more scalable.
  • Let the user decide what some content inside the component can display
  • For example: the navigation bar in the mobile website, in mobile development, almost every page has a navigation bar. The navigation bar must be packaged as a plug-in, such as the nav-bar component. Once we have this component, we can reuse it in multiple pages.
  • The best way to encapsulate is to extract commonality into components and expose differences as sockets
  • Once we have reserved a slot, users can decide what to insert into the slot according to their needs
  • Is it a search box, or text, or a menu. up to the caller to decide

named slot

  1. Basic use of slots<slot></slot>
  2. The default value of the slot<slot>button</slot>
  3. If there are multiple values, when put into the component for replacement at the same time, they will be used as replacement elements together

compile scope

  • An official guideline is given: everything in the parent component template will be compiled in the parent scope; everything in the child component template will be compiled in the child scope.

Scoped slots: ready

  • The parent component replaces the slot's label, but the content is provided by the child component.

Common modular specifications:
CommonJS, AMD, CMD, and ES6 Moudules
ES6 (export export/import import)

Modular implementation of ES6

  • Introduce two js files in the HTML code, and the type needs to be set to module
  • export in a.js
var name = '小明'
var age = 18
var flag = true

function sum(num1,num2) {
    
    
    return num1+num2;
}
if (flag){
    
    
    console.log(sum(20, 10));
}

//1.导出方式一
export {
    
    
    flag,sum
}
//2.导出方式二:
export var num1 = 1000;
export var height = 1.88;
//3.导出函数/类
export function mul(num1,num2) {
    
    
    return num1+num2
}
export class Person {
    
    
    run(){
    
    
        console.log('在蹦包');
    }
}
// class Perosn {
    
    
//
// }
//默认导出(default)
const a = '北京'
export default a
  • import in b.js
//1.导入的是{
    
    }中的定义的变量
import {
    
    flag,sum} from "./aaa.js";

if (flag){
    
    
    console.log('小明是天才,哈哈哈哈哈哈');
    console.log(sum(20, 30));
}

//2.直接导入export定义的变量
import {
    
    num1,height} from "./aaa.js";
console.log(num1);
console.log(height);

//3.导入 export的function
import {
    
    mul,Person} from "./aaa.js";
console.log(mul(30, 50));
const  p = new Person();
p.run();
//4.默认的导入
import aa from "./aaa.js";
console.log(aa);
//5.统一全部导入
import * as aaa from './aaa.js'
console.log(aaa.mul(10, 2));

What is Webpack?

Essentially, Webpack is a static module bundler for modern JavaScript applications.
Understand from two points: modules and packaging
Before ES6, if we want to develop modularly, we must use other tools to allow us to develop modularly.
And after completing the project through modular development, it is necessary to deal with various dependencies between modules and integrate and package them.
One of the cores of Webpack is to allow us to develop modularly and help us deal with dependencies between modules.
And not just JavaScript files, our CSS, images, json files, etc. can be used as modules in webpack.
This is the concept of modularity in webpack.

What is the difference between grunt/gulp and webpack?

Grunt/gulp puts more emphasis on the automation of the front-end process, and modularization is not its core.
webpack puts more emphasis on modular development management, and functions such as file compression and merging, preprocessing, etc. are its attached functions.

install webpack

  • Webpack is modularized and packaged. In order to run normally, webpack must rely on the node environment. In order for the node environment to execute a lot of code normally, it must contain various dependent packages npm tool (node ​​packages manager)
  • To install webpack, you first need to install Node.js. Node.js comes with
    the commands used by the package management tool npm
  • webpack ./src/main.js -o ./dist/bundle.js
  • npm init (initializes the project and generates a package.json file)
  • npm run build (package [need to configure a script "build": "webpack" in pakeage.json])
  • npm install [email protected] --save-dev (development-time dependency)
  • npm install --save-dev css-loader (you also need to configure it in webpack.config.js after installation)
  • npm install --save-dev style-loader (you also need to configure it in webpack.config.js after installation)
  • npm install --save-dev url-loader

env (environment)
converts ES6 syntax into ES5, then you need to use babel
in webpack, we can directly use the loader corresponding to babel
npm install -save-dev babel-loader@7 babel-core babel-preset-es2015
Configure the webpack.config.js file
to repackage, check the bundle.js file, and find that the content has become the difference between ES5 syntax
el and template.
el is used to specify the DOM to be managed by Vue, which can help analyze the instructions and event monitoring in it. etc. And if the template is specified in the Vue instance at the same time, the content of the template template will replace the mounted corresponding el template.
Install vue-loader and vue-template-compiler
npm install vue-loader vue-template-compiler --save-dev
Modify the configuration file of webpack.config.js: ...
package the index.html file into the dist folder, this time You can use the HtmlWebpackPlugin plug-in
HtmlWebpackPlugin plug-in can do these things for us:
-Automatically generate an index.html file (you can specify a template to generate)
-Insert the packaged js file into the body automatically through the script tag
Install the HtmlWebpackPlugin plug-in:
npm install html-webpack-plugin --save-dev
Modify the plugins in the webpack.config.js file:...
js compressed Plugin
- here we use a third-party plugin uglifyjs-webpack-plugin, and the version number specifies 1.1.1, which is consistent with CLI2 -npm
install uglifyjs-webpack-plugin @1.1.1 --save-dev
to build a local server
npm install --save-dev [email protected]
devserver is also an option in webpack, the option itself can set the following attributes:
-contentBase: for that one The folder provides local services. The default is the root folder. Here we need to fill in ./dist
-port: port number
-inline: real-time page refresh
- historyApiFallback: In the SPA page, rely on the history mode of HTML5
- we can configure another one The scripts:–open parameter means to open the browser directly

What is Vue CLI

  • If you simply write a few Vue Demo programs, then you don't need Vue CLI. If you are developing a large project, then you need and must use Vue CLI
  • When using Vue.js to develop large-scale applications, we need to consider things such as code directory structure, project structure and deployment, hot loading, code unit testing; if each project has to manually complete these tasks, it is undoubtedly less efficient, so usually We will use some scaffolding tools to help the Lord complete these things
  • CLI is Command-Line-Interface, translated as command line interface, but commonly known as scaffolding
  • Vue CLI is an official release vue.js project scaffolding
  • Use vue-cli to quickly build a Vue development environment and the corresponding webpack configuration
  • Global installation of Webpack: npm install webpack -g
vue-cli uninstall installation instructions

//Uninstall the version before 3.0
npm uninstall -g vue-cli
yarn global remove vue-cli
//Uninstall the version after 3.0 (you can use this command to uninstall)
npm uninstall -g @vue/cli
yarn global remove @vue/cli

Install the latest version:

npm install -g @vue/cli
or
yarn global add @vue/cli

View all version numbers:

//Query versions before 3.0
npm view vue-cli versions --json
//Query versions after 3.0
npm view @vue/cli versions --json

Install the specified version:

//Install version 2.9.6
npm install -g [email protected]
yarn global add [email protected]
//Install version 4.0.5
npm install -g @vue/[email protected]
yarn global add @vue/[email protected]

View the current version number and help information:

vue -V or vue --version
vue -h or vue --help

Install the version of Vue CLI3. If you want to initialize the project in the way of Vue CLI2, you can install a bridging tool globally.

npm install @vue/cli-init -g

Vue CLI2 initialization project
vue init webpack my-project
Vue CLI3 initialization project
vue create my-project

vue whole family: VueCore (vue core) + vue-router + vuex

The difference between Runtime-Compiler and Runtime-only

In the subsequent development, if you still use the template, you need to choose Runtime-Compiler.
If you use the .vue folder for development in the subsequent development, you can choose Runtime-only

Meet Vue CLI3

There is a big difference between vue-cli 3 and version 2.
Vue-cli 3 is based on webpack 4. Vue-cli 2 is still webpack 3. The
design principle of vue-cli 3 is '0 configuration', and the removed configuration file is in the root directory Yes, directories such as build and config.
Vue-cli 3 provides vue ui commands, provides visual configuration, and is more user-friendly.
Removed the static folder, added a new public folder, and moved index.html to public

Where did the configuration of Vue CLI3 go? You can view the modification through vue ui

ES6 arrow functions

How is this found in the arrow function?

Look up this layer by layer in the outer scope until there is a definition of this.
The arrow function does not have this, and the this inside it points to the scope where it was defined.
The this of an ordinary function is determined by the dynamic scope, which always points to its direct caller. If the function has no direct caller, this is window. In strict mode, if the function has no direct caller, this is undefined.
Using that, you don’t have to worry about the function you use, the arrow function, or something else. It’s a good method, and you don’t have to worry about the differences in the browser’s this pointing.

What is routing (Vue Router)?

  • Routing is a term in network engineering.
  • Routing is the activity of transferring information from a source address to a destination address through an interconnected network. -Wikipedia
  • Uh, what is it? did not understand
  • The router provides two mechanisms: routing and delivery
  • Routing is the determination of the path a packet takes from source to destination
  • Forwarding moves data from an input to the appropriate output
  • There is a very important concept in routing called routing table
  • The routing table is essentially a mapping table, which determines the direction of the data packet.
  • Routing is to display different content or pages according to different url addresses
  • The core of front-end routing is: change the URL, but the page does not refresh as a whole.
  • Backend routing: The backend handles the mapping relationship between URLs and pages.

What is front-end rendering? What is back-end rendering (server-side rendering)?

Front-end rendering: Most of the content of the webpage displayed in the browser is executed by the js code written by the front-end in the browser, and the finally rendered webpage. (It can also be said: the backend returns JSON data, and the frontend uses the pre-written html template to read the JSON data in a loop, concatenate the strings, and insert the page.) Backend rendering: the server directly produces and renders the corresponding HTML page, and returns
it to client to display. For example: jsp page

Separation of front-end and back-end: With the emergence of Ajax, there is a development model of separation of front-end and back-end; the back-end only provides API to return data, and the front-end obtains data through Ajax, and can render the data into the page through JavaScript; and when the mobile terminal ( ios/Android) appears, the backend does not need to do any processing, just use the previous set of API

$router$routethe difference between

$routerIf VueRouteryou want to navigate to a different URL for the instance, use $router.pushthe method
$routethat can be obtained in the current router jump objectpath、query、name 、params

keep-alive meets vue-router

keep-alive is a built-in component of Vue, which can keep the contained component state, or avoid re-rendering.
They have two very important properties:
include - string or regex, only matching components will be cached
exclude - string or regex, any matching components will not be cached
router-view is also a component, if Wrapped directly in keep-alive, all view components matching the path will be cached.

What is Promise?

A very useful feature in ES6 is that Promise
Promise是异步编程的一种解决方案
generally uses Promise as an asynchronous operation to encapsulate when there are asynchronous operations
. When entering the callback function, two parameters will be passed in, resolve and reject, which are themselves functions.

Promise three states

After promise asynchronous operation, there will be three states, which are
Pending (waiting state), for example, a network request is in progress or the timer has not expired.
fullfill (satisfied state), when we actively call back resolve,
we are in this state, and will call back. )

Callback

Pass a function as a parameter into another function, and then call back the function after passing it

Vuex composition and principle

  • Composition: communication between components, global access through store
  • Modification: The only way is to commit a mutation (synchronous) or dispatch an action (asynchronous)
  • Shorthand: introduce mapState, mapGetters, mapActions

Official explanation: Vuex is a state management model specially developed for Vue.js applications.

It takes 集中式存储管理the state of all components of the application and applies rules to ensure that state changes in a predictable manner.
Vuex is also integrated into Vue's official debugging tool devtools extension, providing advanced debugging functions such as zero-configuration time-travel debugging, state snapshot import and export, etc.

Devtools is a browser plugin

  1. Extract a common store object for saving state shared among multiple components
  2. Place the store object in the new Vue object, so that it can be used in all components
  3. You can use the state saved in the store object in other components ( this.$store.state.access the state through the property method this.$store.commit('mutation中方法')to modify the state)

Vuex core concept

State (data single state tree)
Getters (when the data in the component is changed and then used by other components, getters cannot pass parameters by default. If you want to pass parameters, you can only let the getters themselves return another function) Mutations
( state Update: The only way to update the Vuex state (submit Mutation) mainly includes two parts: 1. The event type (type) of the string 2. A callback function handler, the first parameter of the callback function is state.
Actions (Async Actions (Promise))
Modules

Mutation response rules

The state in Vuex's store is responsive. When the data in the state changes, the Vue component will be automatically updated.
This requires us to abide by some rules corresponding to Vuex:
initialize the required properties in the store in advance.
When adding new properties to objects in the state, use the following method:
Method 1 (use Vue.set(obj, 'newProp ', 123))
method 2 (reassign the old object with the new object)

Mutation synchronization function

Normally, Vuex requires that the methods in our Mutation must be synchronous methods.
The main reason is that when we use devtools, devtools can help us capture snapshots of mutations.
But if it is an asynchronous operation, devtools will not be able to track when the operation will be completed.

What are Axios?

Axios is a promise-based HTTP library. Simply put, it can send get and post requests.

Axios Features

  1. XMLHttpRequests can be sent in the browser
  2. You can send http requests in node.js
  3. Support Promise API
  4. Intercept requests and responses
  5. Transform request data and response data
  6. Ability to cancel requests
  7. Automatically convert JSON data
  8. Client support to protect against XSRF attacks

What scenario is Axios used in?

As mentioned in the feature, Axios can be used to send requests from browsers or from Node.js. Projects like Vue, React, Node, etc. can use Axios. If you use Jquery in your project, you don’t need to do anything extra at this time, jquery itself can send requests.

Speaking of CSS

  • display: flex; flex-wrap: wrap;(Wrapping: Determine how many to display according to the width of a line, the default is nowrap without wrapping)
  • justify-content: space-around;(equal score)

Modifier for v-on(@)

  • .native modifier: When we need to monitor the native event of a component, we must add the .native modifier to the corresponding event to monitor

Problems with Better-Scroll scrollable areas

  • Better-Scroll determines how many areas can be scrolled based on the scrollerHeight property
  • Monitor whether each picture is loaded, as long as one picture is loaded, execute refresh() once
  • How to monitor the image loading is complete? Native js monitoring pictures: img.onload = function() {}
  • Listening in Vue: @load = 'method'
  • Call refresh() of scroll

Anti-shake debounce/throttle

The anti-shake debounce/throttle
anti-shake function works:
If we execute refresh directly, the refresh function will be executed 30 times.
You can pass the refresh function into the debounce function to generate a new function

ceiling effect

When you get it, tabControl的offsetTopyou must know how far you have scrolled, and it will start to have a ceiling effect

Guess you like

Origin blog.csdn.net/weixin_46319117/article/details/105391417