note
Scaffold environment structure:
|-— node_modules
|- public
| |—— favicon.ico tab Icon
| |—— index.html main page
|- src
|| - assets main page
| | |-logo.png
|| - components store components
| | |-HelloWorld.vue
| |—— App.vue summarize all components
| |—— main.js entry file
| |—— . Gitignore configuration ignored by git version management
| |—— babel. config. Configuration file for JS Babel
| |—— package.json application package configuration file
| |—— README.md application description file
| |—— package-lock.json package version control file
About different versions of Vue:
- 1.vue.js and Vue runtime. xxx. JS difference
- (1). vue.js is the full version of Vue, including: core functions and template parser.
- (2). vue.runtime.xxx.js is a running version of Vue, which only contains core functions and no template parser
- 2. Because Vue runtime. xxx. JS does not have a template parser, so you can't use template configuration items. You need to use the render function to receive the createElement function to specify the specific content
vue.config.js configuration file
- 1. Use Vue inspect > output JS can view the default configuration of Vue scaffold
- 2. Use Vue config. JS can customize the scaffold. For details, see: https://cli.vuejs.org/zh
ref attribute
- 1. Used to register reference information (id substitutes) for elements or subcomponents
- 2. The real DOM element is obtained on the html tag, and the component instance object (vc) is applied on the component tag
- 3. Usage:
- Marking: < H1 ref = "XXX" ></ h1> <School ref="xxx"/>
- Get: this refs. xxx
Configure porps
Function: let components receive external data
- (1). Transfer data:
<Dome name='xxx'>
- (2). receive data
- First method (receive only)
props: ['name']
- Second method (restriction type)
props: { name: String }
- The third method (restriction type, restriction necessity, specifying default value)
props: { type: String, //type required: true, //necessity default: 'Lao Wang' //Default value
Note: porps is read only Vue bottom layer will monitor your changes to porps. If you make changes, it will issue a warning,
If the business really needs to be modified, please copy the contents of porps into data, and then modify the data in data.
Mixin (mixed)
- Function: the configuration shared by each component can be extracted into a mixed object
- Usage:
- Step 1: define mixing: for example
{ data(){...}, methods: {...} ... }
- Step 2 use blending: for example
(1) Global blending: Vue mixin(xxx)
(2) Local mixing: mixins: ['xxx ']
plug-in unit
- Features: for enhancing Vue
- Essence: an object containing the install method. The first parameter of install is Vue, and the second parameter is the data passed by the plug-in user
- Define plug-ins:
// 1. Global filter Vue.filter('mySlice',function(value) { return value.slice(0,4) }), // 2. Define global instructions Vue.directive('fbind',{ bind(element, binding) { console.log(element,binding) element.value = binding.value }, // When the element containing the directive is inserted into the page inserted(element, binding) { element.focus() }, // When the template where the instruction is located is parsed again update(element, binding) { element.value = binding.value element.focus() console.log('update') }, }), // 3. Configure global mixing (integration) Vue.mixin({ data() { return { x: 200, y: 300 } }, showName() { alert(this.studentName) } }) // Add instance method Vue.prototype.$myMethod = function() {....} Vue.prototype.$myproperty = xxx
- Using plug-ins: Vue use()
scoped style
- Function: make the style locally effective and prevent conflicts
- Writing method: < style scoped >
Summarize the TodoList case
- 1: Component process code:
- (1) Split static components: components should be split according to functions, and their names should not conflict with html elements.
- (2) Implementation of dynamic components: consider the location of data storage, whether the data is in use by a component or some components
- 1. When a component is in use, it can be placed on the component itself
- 2. Some components are in use and placed on their common parent components (state promotion)
- (3) Implement interaction: start with binding events
- 2: props applies to:
- (1) Parent component = = > child component communication
- (2) Child component = = > parent component communication (requires parent to give child a function)
- 3: When using v-model, remember: the value bound to v-model cannot be the value passed from props, because props cannot be modified!
- 4: If the value passed from props is an object type value, modifying the attribute value Vue in the object will not report an error, but it is not recommended.
webStorage
- 1. The storage content size generally supports about 5MB (different browsers may be different)
- 2. Browser through window Localstorage and window The sessionstorage property implements the local storage mechanism
- 3. Relevant API:
- 1.xxxxxStorage.setItem('key','value')
- This method will receive a key and value as parameters, add the key value pair to the storage, and update its corresponding value if the key name exists.
- 2.xxxxxStorage.getItem('key')
- This method takes a key name as a parameter and returns the value corresponding to the key name
- 3.xxxxxStorage.getItem('key')
- This method takes a key name as a parameter and deletes the key name from storage
- 4.xxxxxStorage.clear()
- This method clears all data in the storage
- 1.xxxxxStorage.setItem('key','value')
- 4. Remarks
- 1. The contents stored in sessionstorage will disappear when the browser window closes.
- 2. The content stored in localstorage needs to be cleared manually before it disappears
- 3.xxxxxStorage.getItem(xxx) if the value corresponding to XXX cannot be obtained, the return value of that getItem is null
- 4.JSON. The result of parse (null) is still null
Custom events for components
- 1. A communication mode between components, applicable to: child component = = = > parent component
- 2. Usage scenario: A is the parent component and B is the child component. If B wants to transfer data to a, it needs to bind a custom event to B in a (the callback of the event is in a)
- 3. Binding custom events:
- 1. The first method: in the parent component: < dome @ atguigu = "test" / > or < dome v-on: atguigu = "test" / >
- 2. The second method: in the parent component
<Dome ref='demo'/> ..... mounted(){ this.$refs.xxx.$on('atguigu',this.test) }
- 3. If you want a custom event to be triggered only once, you can use the once modifier or the $once method.
- 4. Trigger custom event: this$ Emit ('atguigu ', data)
- 5. Unbind custom event: this$ off('atguigu')
- 6. Native DOM events can also be bound on the component, and the native modifier needs to be used.
- 7. Note: through this$ refs. xxx.$ On ('atguigu ', callback) when Binding custom events, the callback is either configured in methods or an arrow function is used, otherwise there will be a problem with this pointing!
Global event bus
- 1. A communication mode between components, which is suitable for communication between any components.
- 2. Install the global event bus:
new Vue({ ...... beforeCreate(){ Vue.prototype.$bus = this //Install the global event bus, $bus is the vm of the current application }, ...... }).$mount('#app')
- 3. Use event bus:
- 1. Receive data. If component a wants to receive data, bind a custom event to $bus in component A, and the callback of the event keeps component a itself.
methods: { demo(data){ ...... }, }, mounted() { this.$bus.$on('xxxx',this.demo) },
- 2. Provide data: this$ bus.$ Emit ('xxxx ', data)
- 3. It is better to use $off in the beforeDestroy hook to unbind the events used by the current component.
Message subscription and Publication (pubsub)
- 1. A communication mode between components, which is suitable for communication between any components.
- 2. Use steps:
- 1. Install pubsub: NPM I pubsub JS
- 2. Import: import PubSub from 'PubSub JS'
- 3. Receive data. If component a wants to receive data, it subscribes to messages in component A, and the callback of events keeps component a itself.
methods: { demo(data){ ...... }, }, mounted() { this.pid = pubsub.subscribe('xxx',this.demo) //Subscription message },
- 4. Data provided: PubSub Publish ('xxx ', data)
- 5. It is better to use PubSub. In the beforeDestroy hook Unsubscribe (this. PID) to unsubscribe.
nextTick
- 1. Syntax: this$ Nexttick (callback function)
- 2. Function: execute the specified callback function after the next DOM update rendering
- 3. When to use: after changing the data, some operations should be performed based on the new DOM in the callback function specified by nextTick
Transition and animation of Vue encapsulation
- 1. Function: when inserting, updating or removing DOM elements, add style class names to the elements when appropriate.
- 2. Illustration: (detailed vue official website animation)
- 3. Writing method:
- 1. Ready style:
- Element entry style:
- 1.v-enter: starting point of entry
- 2.v-enter-active: entry process
- 3.v-enter-to: end point of entry
- Style of element departure:
- 1.v-leave: the starting point of departure
- 2.v-leave-active: process of leaving
- 3.v-leave-to: end of departure
- Element entry style:
- 2. Wrap the elements to transition and configure the name attribute
<transition name="hello"> <h1 v-show="isShow">How do you do!</h1> </transition>
- 3. Note: if multiple elements need transition, you need to use: < transition growth >, and each element needs to specify a key value.
- 1. Ready style:
vue scaffold configuration agent
- Method 1
- In Vue config. JS add the following configuration
devServer: { proxy: "http://localhost:5000" }
- explain:
- 1. Advantages: simple configuration. When requesting resources, it can be directly sent to the front end 8080
- 2. Disadvantages: multiple agents cannot be configured, and it is not flexible to control whether requests go through agents.
- 3. Working mode: if the agent is configured according to the above, when the front-end resource does not exist, the request will be forwarded to the server (the front-end resource will be matched first)
- Method 2
- Write Vue config. JS configure specific proxy rules:
module.exports = { devServer: { proxy: { '/api1': { //Match all request paths starting with '/ api1' target: 'http://localhost:8080 ', the basic route of the proxy target changeOrigin: true, pathRewrite: {'^/api1': ''}, }, '/api2': { //Match all request paths starting with '/ api2' target: 'http://localhost:8090 ', the basic route of the proxy target changeOrigin: true, pathRewrite: {'^/api1': ''}, } } } } <!-- changeOrigin Set to true The server receives a message in the request header host Is: loaclhost: 8090, changeOrigin Set to false The server receives a message in the request header host Is: loaclhost: 8080, changeOrigin Default to true -->
- explain:
- 1. Advantages: multiple agents can be configured, and it can flexibly control whether requests go through agents.
- 2. Disadvantages: the configuration is slightly cumbersome and must be prefixed when requesting resources.
slot
- 1. Function: enables the parent component to insert html structure into the specified location of the child component. It is also a communication method in the component, which is applicable to the parent component = = > child component
- 2. Classification: default slot, named slot and scope slot
- 3. Usage:
- 1. Default slot
- In parent component:
<Category> <div>html Structure 1</div> </Category>
- In subcomponents:
<template> <div> <h3>{{title}}classification</h3> <!-- Define slot--> <slot>Slot default content...</slot> </div> </template>
- 2. Named slot
- In parent component:
<Category> <template slot='center'> <div>html Structure 1</div> </template> <template v-slot:center> <div>html Structure 1</div> </template> </Category>
- In subcomponents:
<template> <div> <!-- Define slot --> <slot name='center'>Slot default content...</slot> </div> </template>
- 3. Scope slot:
- 1. Understanding: the data is in the component itself, but the structure generated by the data needs to be determined by the user of the component. (the games data is in the Category component, but the structure traversed by the data is determined by the App component)
- 2. Specific code
- In parent component:
<template scope="atguigu"> <ul> <li v-for="(item,index) in atguigu.games" :key="index">{{item}}</li> </ul> </template> </Category> <Category title="game" > <template scope="{games}"> <ul> <li v-for="(item,index) in games" :key="index">{{item}}</li> </ul> </template> </Category> <Category title="game" > <template slot-scope="{games}"> <ul> <li v-for="(item,index) in games" :key="index">{{item}}</li> </ul> </template> </Category>
- In subcomponents:
<template> <div class="category"> <h3>{{title}}classification</h3> <!-- Define a slot (dig a hole and wait for the component user to fill it) --> <slot :games='games'>I am some default values. When the current user does not pass the specific structure, I will appear 1</slot> <!-- <ul> <li v-for="(item,index) in listData" :key="index">{{item}}</li> </ul> --> </div> </template> <script> export default { name: 'Category', props: ['title'], data() { return { games: ['Red Alert', 'Cross Fire', 'Audition', 'Super Marie'], } }, } </script>
- 1. Default slot
1. Concept
A vue plug-in that implements centralized state (data) management in vue. It centrally manages (reads / writes) the shared state of multiple components in vue applications. It is also a communication mode in components and is suitable for communication between any components.
2. How to use?
When multiple components need to share data
3. Build vuex environment
- 1. Create the file Src / store / index js
import Vue from 'vue' // Introducing vuex import Vuex from 'vuex' <!-- application vuex --> Vue.use(Vuex) // Prepare actions - > to respond to actions in the component const actions = {} // Prepare changes - > for operating data (state) const mutations = {} // Prepare state - > for storing data const state = {} // Create a store and expose it export default new Vuex.Store({ actions, mutations, state })
4. Basic use
- 1. Initialize data, configure actions, configure changes, and operate store js
//Introducing vue core libraryimport Vue from 'vue' // Introducing vuex import Vuex from 'vuex' Vue.use(Vuex) const actions = { <!-- Action added in response component --> JIA(context,value){ // console. Log ('JIA in actions called ', context,value) context.commit('JIA',value) }, } // Prepare changes - > for operating data (state) const mutations = { <!-- Executive plus --> JIA(state, value) { state.sum += value // console. Log ('JIA in changes called ', state,value) }, } // Prepare state - > for storing data const state = { sum: 0 } // Create a store and expose it export default new Vuex.Store({ actions, mutations, state })
- 2. Read data from vuex in the component: $store state. sum
- 3. Read data from vuex in the component: $store Dispatch ('method name in action ', data) $store Commit ('method name in changes', data)
Note: if there is no network request or other business logic, you can bypass the action in the component and write the commit directly instead of the dispatch
5. Use of Getters
- 1. Concept: when the data in state needs to be processed before use, you can use getters processing.
- 2. In state JS to add getters configuration
..... const getters = { bigSum(state){ return state.sum*10 } } <!-- Create and expose store --> export default new Vuex.$store({ ..... getters })
- 3. Read data from the component: $state getters. bigSum
6. Application of four map methods
- 1. mapState method: it is used to help us map the data in state into calculated attributes
computed: { <!-- With the help of mapState Generate calculated properties, sum,school,subject(Object writing) --> ...mapState({he: 'sum',xuexiao: 'school', xueke: 'subject'}), <!-- With the help of mapState Generate calculated properties, sum,school,subject(Array writing) --> ...mapState(['sum','school','subject']), }
- 2. mapGetters method: used to help us map the data in getters into calculated attributes
computed: { With the help of mapState Generate calculated properties, bigSum(Object writing) ...mapGetters({bigSum: 'bigSum'}), With the help of mapState Generate calculated properties, bigSum(Array writing) ...mapGetters(['bigSum']), }
- 3.mapActions method: it is used to help us generate actions dialog, including $state Function of dispatch (xxx)
methods: { // Generate the corresponding method with mapActions, and dispatch will be called in the method to contact actions (object writing method) ...mapActions({incrementOdd:"jiaOdd", incrementWait:"jiaWait"}), // Generate the corresponding method with mapActions. In the method, dispatch will be called to contact actions (array writing method) ...mapActions(["jiaOdd","jiaWait"]), }
- 4.mapMutations method: it is used to help us generate the mutations dialog, that is, $state Function of commit (xxx)
methods: { // Generate the corresponding method with mapMutations, in which commit will be called to contact mutations (object writing method) ...mapMutations({increment:"JIA", decrement:"jian"}), // Generate the corresponding method with mapMutations. In the method, commit will be called to contact mutations (array writing method) ...mapMutations(["JIA", "jian"]), }
remarks: mapActions And mapMutations If you need to pass parameters during use, bind events in the template and pass the parameters. Otherwise, the parameters are event objects
Modularity + namespace
- 1. Purpose: to better maintain data and make multiple data classifications clearer.
- 2. Modify the store js
const countAbout = { namespaced: true, //Open namespace state: { x:1 }, actions: {....}, mutations: {...}, getters: {...}, } const personAbout = { namespaced: true, //Open namespace state: { x:1 }, actions: {....}, mutations: {...}, getters: {...}, } // Create a store and expose it export default new Vuex.Store({ modules: { countAbout, personAbout, } })
- 3. Open the namespace and read the state data from the component:
<!-- Method 1: read directly by yourself --> this.$store.state.personAbout.personList <!-- Mode 2, with the help of mapState read --> ...mapState('countAbout',['sum','school','subject']),
- 4. Open the namespace and read getters data from the component:
<!-- Method 1: read directly by yourself --> this.$store.getters['personAbout/firstPersonName'] <!-- Mode 2, with the help of mapGetters read --> ...mapGetters('countAbout',['bigSum']),
- 5. open namespaces, calling dispatch in the component
<!-- Way one, direct yourself dispatch --> this.$store.dispatch('personAbout/addPersonWang',personObj) <!-- Mode 2, with the help of mapActions --> ...mapActions('countAbout',{incrementOdd:"jiaOdd", incrementWait:"jiaWait"}),
- 6. open namespaces, calling commit in the component
<!-- Way one, direct yourself commit --> this.$store.commit('personAbout/ADD_PERSON',personObj) <!-- Mode 2, with the help of mapMutations --> ...mapMutations('countAbout',{increment:"JIA", decrement:"jian"}),
route
- 1. Understanding: a route is a key value. Multiple routes need to be managed by a router
- 2. Front end Routing: key is the path and value is the component.
1. Basic use
- 1. Install Vue router and command NPM I Vue router
- 2. Application plug-in Vue use(VueRouter)
- 3. Write router configuration item
- Introducing VueRouter
import VueRouter from 'vue-router' // Introducing luyou components import About from '../components/About' import Home from '../components/Home' // Create a router instance object to manage a group of routing rules export default new VueRouter({ routes: [ { path: '/about', component: About }, { path: '/home', component: Home } ] })
- 4. Realize switching (active class can configure highlight style)
<router-link class="list-group-item active" to="/about">About</router-link>
- 5. Specify display location
<router-view></router-view>
. several points for attention
- 1. Routing components are usually stored in the pages file, and general components are usually stored in the components folder.
- 2. By switching, the routing component is hidden. By default, it is destroyed and loaded when necessary.
- 3. Each component has its own $route attribute, which stores its own routing information.
- 4. There is only one router in the whole application, which can be obtained through the $router attribute of the component.
3. Multi level routing
- 1. Configure routing rules and use the children configuration item:
routes: [ { path: '/about', component: About }, { path: '/home', component: Home, children: [ //Configure child routing through children { path: 'news', //Be sure not to write: / news here component: News, }, { path: 'message',//Do not write: / message here component: Message, } ] } ]
- 2. Jump (to write the complete path):
<router-link to="/home/news">News</router-link>
4. query parameters of route
- 1. Transfer parameters
<!-- Jump route and carry parameters, to String writing --> <!-- <router-link to="/home/message/Detail?id=666&title='Hello'">Jump</router-link> --> <!-- Jump route and carry query Parameters, to Object writing of --> <router-link :to="{path: '/home/message/Detail',query: { id: 666, title: 'Hello' }}">Jump</router-link>
- 2. Receiving parameters:
$route.query.id $route.query.title
5. Named route
- 1. Function: it can simplify route jump.
- 2. How to use
- 1. Name the route:
{ path: '/home', component: Home, children: [ { path: 'news', component: News, }, { path: 'message', component: Message, children: [ { name: 'hello', //Name the route path: 'welcome', component: Hello, } ] } ] } ``` - 2.Simplified jump: ```javascript <!-- Before simplification: a complete path is required --> <router-link to="/home/message/welcome">Jump</router-link> <!-- Simplified: jump directly by name --> <router-link :to="{name:'hello'}">Jump</router-link> <!-- Simplified writing fit transfer parameters --> <router-link :to="{name: 'hello',query: { id: 666, title: 'Hello' }}">Jump</router-link>
6. params parameters of route
- 1. Configure the route and declare to receive params parameters
{ path: '/home', component: Home, children: [ { path: 'news', component: News, }, { path: 'message', component: Message, children: [ { name: 'xiangqing', path: 'detail/:id/:title', //Receive params parameters using placeholders component: Detail, } ] } ] }
- 2. Transfer parameters
<!-- Jump route and carry params Parameters, to String writing --> <router-link :to="`/home/message/detail/666/Hello`">Jump</router-link> <!-- Jump route and carry params Parameters, to Object writing of --> <router-link :to="{name: 'xiangqing', params: { id: 666, title: 'Hello' }}">Jump</router-link>
- Special note: when the route carries params parameters, if the object writing method of to is used, the path configuration item cannot be used, but the name configuration must be used!
- 3. Receiving parameters
$route.params.id $route.params.title
7. porps configuration of routing
- Function: make it easier for routing components to receive parameters
{ name: 'xiangqing', path: 'detail/:id/:title', component: Detail, // The first way to write props is that the value is an object, and all key values in the object will be passed to the Detail component in the form of props props: {a: 1, b: 'hello'}, // The second way to write props is Boolean. If the Boolean value is true, all params parameters received by the route will be passed to the Detail component in the form of props props: true, // The third way to write props is that the value is a function. Each set of key values in the object returned by the function will be passed to the Detail component through props props($route){ console.log($route) return {id: $route.params.id, title: $route.params.title} } }
8. replace attribute of
- 1. Function: control the mode of operating browser history during route jump
- 2. Browser history is written in two ways: push and place. Push is to add history and replace is to replace the current record. The default value for route jump is push
- 3. How to start the replace mode: < router link replace..... > News</router-link>
9. Program route navigation
- 1. Function: route jump is realized without the help of < router link >, making route jump more flexible
- 2. Specific code
<!-- $router Two API --> this.$router.push({ name: 'details', query: { id: xxx, title: xxx } }) this.$router.replace({ name: 'details', query: { id:xxx, title:xxx } }) this.$router.back() //back off this.$router.forward() //forward this.$router.go(-2) //You can specify (forward and backward several pages)
10. Cache routing component
- 1. Function: keep the routing components not displayed mounted and not destroyed.
- 2. Specific code
<keep-alive include="News"> <router-view></router-view> </keep-alive>
11. Two new life cycle hooks
- 1. Function: the two hooks unique to the routing component are used to capture the activation status of the routing component.
- 2. Specific name:
- 1. Triggered when the activated routing component is activated
- 2. Triggered when the deactivated routing component is deactivated
12. Route guard
- 1. Function: to control the route permissions
- 2. Classification: Global guard, independent guard and internal guard
- 3. Global guard
- //Global pre route guard - called during initialization and before each route switch
router.beforeEach((to,from,next)=>{ console.log('Pre routing guard',to,from) if(to.meta.isAuth) { //Determine whether authentication is required if(localStorage.getItem('school') === 'atguigu') { next() //Release }else { alert('The school name is incorrect. You have no permission to view it!') } }else { next() } })
- //Global post route guard - called during initialization and before each route switching
router.afterEach((to,from)=> { console.log('Post routing guard',to,from) document.title = to.meta.title || 'music' //Modify the title of the page })
- 4. Exclusive guard:
beforeEnter: (to,from,next)=> { console.log('Pre routing guard', to, from) if(to.meta.isAuth){ if(localStorage.getItem('school') === 'atguigu') { next() }else { alert('The school name is incorrect. You have no permission to view it!') } }else { next() } }
- 5. Guard inside the assembly:
//Entry guard: called when entering the component through routing rules beforeRouteEnter (to, from, next) { } //Leave guard: it is called when leaving the component through routing rules beforeRouteLeave (to, from, next) { }
13. Two working modes of router
- 1. For a url, what is the hash value# The following content is the hash value.
- 2. The hash value will not be included in the http request, that is, the hash will not be brought to the server
- 3.hash mode:
- 1. The address always carries a # number, which is not beautiful
- 2. If the address is shared through a third-party mobile app in the future, if the app verification is strict, the address will be marked as illegal
- 3. Good compatibility
- 4.history mode:
- 1. The address is clean and beautiful
- 2. Compatibility is slightly worse than hash mode
- 3. When the application is deployed online, it needs the support of back-end personnel to solve the problem of refreshing page 404.