1, Understanding Vue
Author: you Yuxi
Progressive framework: select the tools in the framework according to your own needs. VUE does not require you to accept and use all its functions and features at one time
Vue
Data driven
Progressive framework
Software design pattern based on MVVM
React
Develop the most rigorous framework for large projects
Anagle
It is applicable to large projects. The project development is heavy and inflexible
The difference between Vue and jquery (cleaning)
Native JS
Broom, dustpan, mop
Jquery
Dyson vacuum cleaner
Vue
Sweeping robot (nanny)
2.MVVM (software design pattern)
Vue.js is designed according to this pattern
M: model data model
5: V iew view layer
VM: view model
Data model is modified = > notify VM = > notify View of the update in response
After the View is changed = > notify VM = > notify Model data Model to update data
3. Installation
4. Life cycle
vue instances are created, mounted, updated, and finally destroyed. This whole process is called the life cycle of vue
Lifecycle hook function:It is convenient to operate the current stage vue example // Initialize build phase beforeCreate vue Before the instance initialization is completed, the vue Initialization of events and properties, but they cannot be accessed vue In the instance data,methods created vue After instance initialization, you can access the data and methods inside the instance // Mount phase beforeMount The template parsing is completed, but the data is not bound to the template mounted vm.$el fictitious dom replace el Dom,Data binding completed/dom Tree rendering. // Update phase beforeUpdate Data and modification, virtual dom Also built, but not rendered to the page updated Updated virtual dom Node, successfully rendered to the page // Destruction stage this.$destroy() beforeDestroy vue You can also access the instance before it is destroyed destroyed vue The events, listeners and subcomponents bound on the instance are destroyed and cannot be accessed vue Examples
5. Template syntax
Text interpolation
{{msg}} renders the fields in the data model into the page with double braces
{{msg + 'Nihao'}} js expressions can be placed inside double braces
instructions
v-bind: dynamically bind attributes on elements
v-bind:title abbreviation = >: title = "title"
v-html: binding HTML code snippets
Rich Text Editor
Formatted content = > corresponding html code fragment
v-on: dynamic binding event
v-on:click="clickHandler"
Abbreviation = > @ Click = "clickHandler"
conditional rendering
v-if v- else
v-show
difference:
V-IF and v-else can display and hide dom nodes by controlling their rendering
v-show controls the display in the css style of the dom node to display and hide
When a component is frequently displayed and hidden, v-show is better
v-if will render the dom tree frequently, which will occupy resources and affect the running efficiency of the code
List rendering
v-for
use:
<ul> <li v-for="(item, index) of arr" :key="index">{{item}}{{index}}</li> </ul> class binding :class <div :class="{ active: isActive }">Block level element</div> <div :class="[active1, box1]">Block level element</div> <div :class="[isActive? active1 : box1]">Block level element</div> style binding :style <div :style="{color: 'red', fontSize: '24px'}">Block level element</div> <div :style="style1">Block level element</div> <div :style="[style1, style2]">Block level element</div>
2, Basic properties of Vue
1. Event mechanism
Event transmission parameters
@click="handler('1',$event)"
handler(id,event) {}
Event modifier
. stop stop event bubbling
. prevent block event default behavior
. capture executes event handling functions during the event capture phase
. self triggers the handler only if event.target is the current element itself
The. Once event handler performs unbinding once
The default behavior of. passive scrolling event (i.e. scrolling behavior) will be triggered immediately. It is generally used in conjunction with scroll to improve the performance of the mobile terminal
Key modifier
.enter,.tab,.delete,.esc,.space,.up,.down,.left,.right
.ctrl,.alt,.shift,.meta
Mouse modifier
.left,.right,.middle
2. Form
Bidirectional data binding
Through the instruction of v-model
View modification = > ViewModel = > model modification data
model data change = > ViewModel = > View update
Modifier
. lazy v-model is triggered by change event instead of input
. number automatically converts the output value of the current input box to type number
. trim eliminates spaces before and after the output value
form control
3. Calculation attribute
A variable can be calculated and then output
computed: {
total() {
return this.a + this.b
}
}
4. Listener
Use listeners when you need to perform asynchronous or expensive operations when data changes
watch: {
//Basic data type
a(newVal, oldVal) {},
//Reference data type (if normal listening is used, only the change of reference address can be monitored)
obj: {
handler(newVal, oldVal) {},
deep: true
},
//Listen for a specific value within a reference data type
'obj.username': {
handler(newVal, oldVal) {},
deep: true
}
}
3, Vue component mechanism
1. General
The component can expand HTML elements and internally encapsulate reusable HTML, CSS and JS code fragments.
A component is similar to a vue instance. There is a template attribute inside the component, which is used to specify the template,
There is an el attribute inside the vue instance, which is used to specify the template
2. Component definition
let component = {
data() {
return {
//Returns a unique copy of the object value to ensure that the internal data of the reused components will not affect each other
msg: "I am the data of the component"
}
},
Template: < div > < p > I am the component < / P > < H1 > {{MSG}} < / H1 > < / div >
}
3. Component registration
Globally registered components can be used within any vue instance or component
Locally registered components can only be used within the currently registered instance or component
It is similar to global variables and local variables in js
1) Global registration
Vue.component('my-com', component);
If a component is called by multiple other components, global registration is better
2) Local registration
If a component is called multiple times within an instance or component, local registration is better
new Vue({ el: '#app', data: {}, components: { 'my-com': component } })
4. Component interaction
1) Pass parameters from parent component to child component
The parent component uses the prop attribute to pass parameters to the child component
<div id="app"> <my-com :title="title" msg="hello"></my-com> </div>
Dynamic parameter transfer
No: passed constant string
There are: pass boolean, number, object, array and variable
Subcomponent accept parameters
Let component = {props: ['title ','msg'],} props verification let component = {props: {Title: {type: string, / / verify the data type. required: true, / / the parameter must be passed. / / the basic data type is written directly after default. Default: 'hello', / / the default value of the current parameter. / / reference the data type and return an object or array in the form of a factory function. Default() {return {}} validator (VAL) {/ / custom verifier return val.length > 3}}},}
2) The child component passes parameters to the parent component
```
<my-com @son-handler="fatherHandler" msg="hello">
let component = { data() { return { comMsg: 'I am sub component data' } }, template:` <div> <button @click='clickHandler'>Send event</button> </div> `, methods: { clickHandler() { this.$emit('son-handler', this.comMsg) } } } new Vue({ el:'#app', data: { fatherDate: '' }, methods: { fatherHandler(val) { // val is the parameter this.comMsg carried by the subcomponent when sending events this.fatherDate = val } }, components: { myCom: component } }) 3)Unidirectional data flow Parent prop The update of data will flow down to the sub components, but not vice versa The parent component can modify the data in the child component, while the child component cannot directly modify the data in the parent component effect: Prevent the child component from accidentally changing the state, which will affect the state or data in the parent component
5. Slot
1) Ordinary slot
<my-com>hello vue</my-com> let com = { template: ` <div> <slot></slot> // Default slot </div> ` } ``` 2)Named slot <my-com> <template v-slot:header> Abbreviation #header I'm the head content </template> <template v-slot:default> <p>hello component</p> <h3>Hello component slot</h3> </template> <template v-slot:footer> I am the footstep content </template> </my-com> let com = { template: ` <div> <header> <slot name="header"></slot> // Named slot </header> <main> <slot name="default"></slot> // Anonymous slot </main> <footer> <slot name="footer"></slot> // Named slot </footer> </div> ` } 3)Scope slot <my-com> <template v-slot:header="scope"> {{scope.msg}} // Scope is a scope object, which encapsulates the msg data passed by the sub components. You can use the deconstruction of the object I'm the head content </template> <template v-slot:default> <p>hello component</p> <h3>Hello component slot</h3> </template> <template v-slot:footer> I am the footstep content </template> </my-com> let com = { data() { return { msg: 'I am component data' } } template: ` <div> <header> <slot name="header" :msg="msg"></slot> // Named slot </header> <main> <slot name="default"></slot> // Anonymous slot </main> <footer> <slot name="footer"></slot> // Named slot </footer> </div> ` }
6. Dynamic components
<component is="my-com1"></component> // Static component <component :is="current"></component> // Dynamic component
4, day04 reusable technology
1. Mixing
Blending rules:
1) The data in the data model will be merged recursively, and the attribute with the same name will appear, and the data in the component shall prevail
2) Constructors with the same name will be merged into an array, in which all functions will be called. The mixed hook will be executed first, and the hook of the component will be executed last
3) The merging of internal objects is similar to the merging of components and methods into one object. In case of conflict, the one in the component shall prevail
Global blending
Vue.mixin({})
Local mixing
mixins: [mixin]
2. User defined instructions
There are five hook functions inside the instruction
bind(){}
inserted(){}
update(){}
componentUpdated(){}
unbind(){}
Each hook function has four formal parameters
el the dom object bound by the current instruction
Binding details of the current value binding instruction
Virtual dom node generated by vNode Vue compilation
A virtual dom node on the oldNode. This parameter has an argument only when the update and componentUpdated hooks are triggered
3. Filter
Usage scenario
{{timestamp | fmtDate}}
v-bind="msg | fmtText"
Global registration
Vue.filter('fmtDate', (val) => {
return ...val
})
Local registration
filters: {
fmtDate(val) {
return ...val
}
}
4.render function
render(createElement) {
return createElement(nodeName,props,childVnode)
}
Description of internal parameters of createElement function
nodeName: tag name
props: configuration information of this element
'class',style,attrs,props,domProps,On,nativeOn
childVnode: child virtual node, generally an array, indicating that there are multiple child elements
5.plugin
The plugin plug-in needs to provide an install method
Call the plug-in before the vue instance is built
Ensure that the created vue instance can access the global methods or properties in the plug-in
Vue.user(MyPlugin)
let vm = new Vue({})
5, Vue router routing manager
vue router is a plug-in of vue, which is used to provide routing function.
Through the change of route, the components can be loaded dynamically to achieve the purpose of developing single page program.
1. Basic use
1) Declaration component
let com1 = {template:`<div>this is com1</div>`} let com2 = {template:`<div>this is com2</div>`} let com3 = {template:`<div>this is com3</div>`} 2)Declaration router router Is a router object, routes Is the routing list let router = new VueRouter({ routes: [ { path: '/a', // Routing address component: com1,// Corresponding components name: 'comA', // Set a name for the route to facilitate jump using name redirect: '/c', // redirect alias: '/coma', // alias }, { path: '/b', component: com2 }, { path: '/c', component: com3 }, ] }) 3)Route registration stay vue Register the route in the root instance of let vm = new Vue({ el: '#app', router: router }) 4)Routing usage <router-link to="/a">A assembly</router-link> <router-link to="/b">B assembly</router-link> <router-link to="/c">C assembly</router-link> // The route viewport is used to load the components corresponding to the route <router-view></router-view> 2.Dynamic routing 1)statement let router = new VueRouter({ routes: [ // Dynamic routing parameters start with a colon { path: '/user/:username/:id', component:com1 } ] }) <router-link to="/user/zhangsan/1001"></router-link> 2)Get the parameters carried by the route (the parameter value will be set to this.$route.params Medium) /user/zhangsan/1001 and/user/lisi/1002 Will map to the same component, When dynamic routing changes occur within a component, vue Component instances are reused without being re destroyed and re created When dynamic routing changes occur inside the component, you can use it when you want to listen for routing parameter changes watch monitor $route,Or use the navigation guard inside the component let com1 = { data() { return { id: null, username: null } }, template: ``, created() { // In the created hook function, you can only get the parameters carried at one time, not continuously this.id = this.$route.params.id; this.username = this.$route.params.username; }, watch() { // Using the watch listener, you can continuously monitor the changes of parameters carried in the router object $route(to, from) { this.id = to.params.id; this.username = to.params.username; } } } 3.Routing guard 1)introduce As its name suggests, vue-router The navigation guard provided is mainly used to guard navigation by jumping or canceling. Each guard method receives three parameters: to: Route Destination routing object to be entered from: Route The route that the current navigation is leaving next: Function Be sure to call this method to resolve This hook allows the route jump to continue next(): Proceed to the next hook in the pipeline (continue to complete the navigation jump) next(false): Interrupt the current navigation. next('/') perhaps next({ path: '/' }): Jump to a different address. Guards are asynchronously parsed and executed, navigating in all guards resolve I've been waiting until I finished. 2)Global guard let router = new VueRouter({ routes: [ {...} ] }) // Global front guard router.beforeEach((to, from, next) => { .......Intercept operation next(); // next(false); }) // Global post guard router.afterEach((to, from) => { .......After operation }) 3)Route exclusive guard let router = new VueRouter({ routes: [ { path: '/a', component: com1, beforeEnter(to, from, next) { .......Intercept operation next(); } } ] }) 4)Component internal guard let com1 = { data(){ return {} }, template: ``, // Intercept before entering the current component beforeRouteEnter(to, from, next) { .......Intercept operation next(); }, // Triggered when the route changes in the current component beforeRouteUpdate(to, from, next) { .......Intercept operation next(); }, // Triggered before leaving the current component beforeRouteLeave(to, from, next) { .......Intercept operation next(); } } 4.Nested Route Pin shape layout: upper head, left navigation bar, right content area Definition of nested routes(children Property) let router = new VueRouter({ routes: [ { path: '/student', component: comStu, children: [ { path: 'grade', component: comGrade }, { path: 'register', component: comRegister }, ] } ] }) use The first level route corresponds to one router-view The secondary route corresponds to one router-view 5.Programming navigation 1)this.$router.push() // Add a new record in the history stack this.$router.push({ path: '/a' }) this.$router.push({ name: 'comA' }) Route jump and carry parameters · route path Jump and query Use with this.$router.push({ path: '/a', query: { username: 'zhangsan' } }) · name name Jump and params Use with this.$router.push({ name: 'comA', params: { age: 12 } }) Parameter acquisition In the target component of the jump, as long as it can access $route You can get the parameters carried by the jump For example, in the target component created(){ console.log(this.$route.params) console.log(this.$route.query) } query Communication participation params Transmission parameter difference 1.query Parameter transfer parameters are saved in url In the address bar, splice it in the form of query string 2.In terms of security, params Safer, query It will be displayed in the address bar, which is easy to cause data leakage 3.When refreshing the page, query The data in is not affected, and params The data in the disappears directly 2)this.$router.replace() // Directly replacing the current route will not generate a new history 3)this.$router.go() // Internally, it accepts integers with positive or negative values as parameters. Positive numbers are forward and negative numbers are backward (in History) 6.Routing mode 1)Modify routing mode let router = new VueRouter({ // mode: 'hash', mode: 'history', // The mode attribute modifies the routing mode, which defaults to the hash mode routes: [] }) hash Routing and history Differences in routing: 1.hash The route is in the address bar URL There are#,and history Route no#, and more streamlined 2.Press enter to refresh, hash The route will be loaded into the page corresponding to the address bar, and history The route usually reports an error at 404 (Refresh is a network request, history Routing requires back-end support). 3.hash Routing supports lower versions of browsers, and history Routing is HTML5 New API. 4.hash The characteristic is that although it appears in URL In, but not included in http The request is in progress, so it has no impact on the back end, So change hash The page will not be reloaded, so it is also necessary for single page applications. 5.history Using the browser's history stack, there were back,forward,go Method, then in HTML5 Added in pushState()and replaceState()Methods (supported by a specific browser), which provide the function of modifying history, However, during modification, although the current URL,However, the browser will not immediately send a request to the back end. #### 6, Vuex state manager 1.introduce Vuex It's a special Vue.js State management mode of application development. It uses centralized storage to manage the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable way. Application scenario: Communication between components at the same level let comA = {} let comB = {} 2.Basic usage: 1)state(be similar to vue Instance data) Where data is stored, each vue The public variables in the instance are extracted for unified management state: { msg: 'hello vuex' } stay vue In, get the information stored in vuex The status of can be obtained directly or through auxiliary functions computed: { count() { return this.$store.state.count } // perhaps ...Vuex.mapState(["count"]) } 2)getters(be similar to vue In the instance computed) Used to state The static data in is calculated and then returned getter: { reMsg(state) { return state.msg.toUpperCase() } } stay vue Can be accessed by calculating properties computed: { reMsg() { return this.$store.getters.reMsg } // perhaps ...Vuex.mapGetters(["reMsg"]) } 3)mutations(mutation) change Vuex of store The only way to the status in is to commit mutation,Must be a synchronous operation. mutation The first argument to the function is state ,The second parameter is to accept the mutation Arguments passed by the user when mutations: { SET_MSG(state, payload) { state.msg = payload } } Can be in vue Submit mutation in life cycle hook or methods Mapping mutation method in created() { // The first parameter is the name of the mutation method, and the second parameter is the passed argument this.$store.commit('SET_MSG', 'hello mutation') } methods:{ ...Vuex.mapMutations(['SET_MSG']) } 4)actions(action) Method used to store asynchronous requests,action Submitted is mutation,Thus indirect changes state Status in actions An asynchronous request in accepts a formal parameter-context(Context object) Available context.state obtain state Available context.getters obtain getters Available context.commit()Submit mutation Available context.dispatch()Distribution action actions: { async findAll(context) { let res = await axios.get('http://...'); // Submit mutation context.commit('SET_MSG', res.data.data) } } Can be in vue Distribute actions in the lifecycle hook or methods Medium mapping actions Methods in created() { // Parameter 1 is the name of the asynchronous function, and parameter 2 can pass arguments this.$store.dispatch('findAll') } methods:{ ...Vuex.mapActions(['findAll']) } 5)case-Define state machine instances let store = new Vuex.Store({ state: { msg: 'hello vuex' }, getters: { reMsg(state) { return state.msg.toUpperCase() } }, // mutation mutations: { SET_MSG(state, payload) { state.msg = payload } }, // action actions: { async findAll(context) { let res = await axios.get('http://'); // Submit mutation context.commit('SET_MSG', res.data.data) } } }) 6)adopt store Inject state machine instances into let vm = new Vue({ el: '#app', store }) 3.auxiliary function Vuex The constructor provides methods to quickly map data and methods Use object deconstruction to deconstruct the internal auxiliary functions let { mapState, mapGetters, mapMutations, mapActions } = Vuex use computed: { ...mapState(['msg']), // State mapping ...mapGetters(['reMsg']) // Calculate attribute mapping }, methods: { ...mapMutations(['SET_MSG']), // Mutation mapping ...mapActions(['findAll']) // Action mapping } 4.Modular development 1)objective Due to the use of a single state tree, all the states of the application will be concentrated in a relatively large object. When the application becomes very complex, store Objects can become quite bloated. In order to solve the above problems, Vuex Allow us to store Split into modules( module). Each module has its own state,mutation,action,getter,Even nested sub modules. namespaced Indicates that the namespace is set 2)use let moduleA = { namespaced: true, state() { return {} }, getters: {}, mutations: {}, actions: {} } let moduleB = { namespaced: true, state() { return {} }, getters: {}, mutations: {}, actions: {} } let store = new Vuex.Store({ modules: { // Rename the state machine module a: moduleA, b: moduleB } }) let vm = new Vue({ el: '#app', data: {}, computed: { // Mapping status. The first parameter is the name of the module ...mapState('a',['aData']), ...mapState('b',['bData']), // Mapping calculation attribute. The first parameter is the name of the module ...mapGetters('a',['reAData']), ...mapGetters('b',['reBData']), }, methods: { // Mapping mutation ...mapMutations('a', ['SET_ADATA']), ...mapMutations('b', ['SET_BDATA']), // Mapping action ...mapActions('a', ['findAll]) ...mapActions('b', ['query]) }, created(){ this.findAll() // Call / execute method }, store: store })
7, Vue webpack
Website https://webpack.docschina.org
file https://webpack.docschina.org/concepts/
Introduction: in essence, webpack is a front-end resource building tool and a static module packaging tool for modern JavaScript applications.
When webpack processes an application, it will build a dependency graph internally,
This dependency graph maps to each module required by the project and generates one or more bundle s.
Global download package
cnpm install -g webpack webpack-cli
Or cnpm I - G webpack webpack cli
Partial download package
Initialize project npm init -y
Download package
cnpm i --save-dev webpack webpack-cli
Or cnpm I - D webpack webpack cli
Five modules
Entry
Output
loader (module)
Plug in
Mode
1. Entrance
The entry point indicates which module should be used by the webpack as the beginning of building its internal dependency graph. After entering the entry point, the webpack will find out which modules and libraries are (directly and indirectly) dependent on the entry point.
The default value is. / src/index.js, but you can specify one (or more) different entry starting points by configuring the entry property in the webpack configuration. For example:
webpack.config.js
module.exports = {
//Single entry
entry: './path/to/my/entry/file.js',
//Multiple entry
entry: {
app: './src/app.js',
adminApp: './src/adminApp.js'
}
};
2. Output
The output attribute tells webpack where to output the bundle s it creates and how to name these files. The default value of the main output file is. / dist/main.js, and other generated files are placed in the. / dist folder by default.
You can configure these processes by specifying an output field in the configuration:
webpack.config.js
const path = require('path');
module.exports = {
entry: './path/to/my/entry/file.js',
output: {
//filename: 'my-first-webpack.bundle.js',
filename: './js/my-first-webpack.bundle.js',
path: path.resolve(__dirname, 'dist'),
}
};
What is the path module? It is a Node.js core module used to operate file paths. resolve() is used to splice paths
3.loader
Webpack can only understand JavaScript and JSON files, which is the built-in capability of webpack out of the box. loader enables webpack to process other types of files, convert them into effective modules for application use, and add them to dependency diagrams.
At a higher level, in the configuration of webpack, loader has two attributes:
test attribute to identify which files will be converted.
The use attribute defines which loader should be used during conversion.
webpack.config.js const path = require('path'); module.exports = { output: { filename: 'my-first-webpack.bundle.js' }, module: { rules: [ { test: /\.html$/, use: 'html-loader' } ] } };
4. Plug in
loader is used to convert some types of modules, while plug-ins can be used to perform a wider range of tasks, including packaging optimization, resource management and injection of environment variables.
To use a plug-in, you only need to require() it and add it to the plugins array. Most plug-ins can be customized through options. You can also use the same plug-in multiple times for different purposes in a configuration file. In this case, you need to create a plug-in instance by using the new operator.
webpack.config.js const HtmlWebpackPlugin = require('html-webpack-plugin'); // Installation via npm const webpack = require('webpack'); // Used to access built-in plug-ins module.exports = { module: { rules: [ { test: /\.txt$/, use: 'raw-loader' } ] }, plugins: [ new HtmlWebpackPlugin({template: './src/index.html'}) ] }; In the example above, html-webpack-plugin Build for application HTML A file and automatically inject all generated files bundle.
5. Mode
By selecting one of development, production or none to set the mode parameter, you can enable webpack's built-in optimization in the corresponding environment. Its default value is production.
6.=entry=======
stay webpack.config.js In the file module.exports = { //Single entry //entry:'./src/js/index.js', //Multiple entry entry: { index: './src/js/index.js', index2: './src/js/index2.js' }, }
7.=output=======
stay webpack.config.js In the file const {resolve} = require('path'); module.exports = { output: { //Single outlet //filename: './js/built-dev.js', //Multi export filename: './js/[name]-built-dev.js', // Output path write absolute path // __The variable of dirname nodejs represents the absolute path of the directory of the current file path: resolve(__dirname, 'build') } }
8.=loader module=======
stay webpack.config.js In the file module.exports = { module:[ //Configuration of loader .... ] }
9. Escape js files and exclude files in node_modules
babel-loader install cnpm i -D @babel/core @babel/preset-env babel-loader to configure { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } }