Vue notes
1. MVVM (Two-way data binding)
- Model Data model (JS object)
- ViewModel (vUE instance)
- View (HTML + CSS)
Vue instance implements intermediate bridge render(data) => view
Developers only need to care about data changes and view updates to vUE
2. Progressive understanding
- Declarative rendering (don’t care how it’s implemented)
- Component system
- Client Routing (VUe-Router)
- Large-scale State Management (VUEX)
- Build Tools (VUE-CLI)
3. The two core points of vUE
1. Data changes in response
When data changes -> View updates automatically
2. View components of components
UI pages are mapped into a tree of components divided into maintainable components. Reusable. Testable
4. Vue installation method single file
1. Import CSDN files
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
Copy the code
2. Install using NPM
NPM install Vue Installs the vUE package
Then use script to introduce node_modules/vue/dist/vue.js
5. A vUE constructor after introducing vUE
let vm = new Vue({
el:""-> Specify the part (view) that vUE needs to manage. It cannot be mounted to HTML and bodydata: {msg:' ' // The vm proxy can fetch the contents of the vm instance}})Copy the code
El :”” You can specify an HTML part, just like querySelector
Data :{} VM constructs the object where the data model VUE is used to store data
6 Display data in the view
You can use {{}} in the managed DOM to use the data in the data and the view changes as the data changes
<div id='app'>{{msg}}</div>
Copy the code
{{}} can be placed in an expression to place an assignment statement value ternary operator
{{msg=='huaixu'?1:0}}
Copy the code
7. View control data
Form element modification Content binding view modification
Form elements -> INPUT checkbox Textarea radio Select
Vue directives -> are just interline attributes in the DOM and Vue gives those attributes meaning to do something special all directives start with a V – value attribute and by default vUE ignores select Checked none of that makes sense
V-model => bidirectional binding of form and data
This value is converted to Boolean if there is only one chebox. If true, this value is selected
If you have more than one you need to use the value property and the data type is array and the selected data will be added to the value
<input type='text' v-model='msg'>V-model will assign the value of MSG to the input box, and the change of the value of the input box will affect the data<input type='checkbox' v-model='msg' value='strawberry'>Data :{MSG :[]} checkBox If selected will write the value to its bound arrayCopy the code
Modifiers in v-Models
.number does not modify data if it is not a number. Lazy Modifies data only when the mouse is clicked elsewhere
V-text => Bind data in dom
Use {{}} when the network or web page load slowly, it will appear raw state, so use V-text or write the imported JS file before (not recommended).
V-once => Binding is performed only once. Data is not refreshed when data changes again
<div v-once></div>
Copy the code
V-html => Render HTML string as HTML, must be trusted HTML (possibly with vulnerabilities)
Using data directly will display the values of the data directly, but some may be HTML code, so you can use V-HTML to display the code as AN HTML structure
8. Changes in data response
Vue loops through all data in data (data hijacking) adding getter setters in turn
1. Initialize variables before using them; otherwise, new attributes will not cause page refresh
New Vue ({el: ' ', data: {a: {school: ""}}}, {{a.s chool}} - > attribute of an object in view use the dataCopy the code
2. Vm. $set() this method can add responsive changes to the object
A = {school:’ ZZZZZ ‘}
9. Array data in data
1. Changing an item in the array cannot be monitored
2. You cannot change the length of the array
data:{ arr: ['1'.'2'.'3']}
// Error demo vm.arr[0] = 100;
// Error vm.arr.length -=2;
Copy the code
Pop Push Shift unshift sort Reserve splice
4. And the method of traversing the number group
vm.arr = vm.arr.map(item= > item*3) can cause a page refreshCopy the code
10.v-for
Previous loop data -> concatenate string innerHTML
Vue provides an instruction v-for to solve the loop problem more efficiently and will reuse the original mechanism
Add the V-for attribute to whoever you want to loop. The default is value of data
<div v-for='item in items'>{{item}} </div>
Copy the code
Let’s say that one argument is a subitem and the second argument is item index in arr
<div v-for='(item,index) in items'>{{item}} ---{{index}} </div>
Copy the code
Other uses of V-for
<div v-for="a in 'aaaa'">{{a}} </div><div v-for='a in 10'>{{a}} </div>
Copy the code
The V-for object gets every item in it
<div v-for='(value,key,index) in object'>{{index}}:{{key}}:{{value}} </div>
Copy the code
11. V – on vue events
Before the add event method – > access object Add event | inline binding method is the partial method bindings on the window
Vue binding event instruction V-ON: short for event name @event name
Event names with parameters can be written without parameters
<div v-on:click=''> </div>
Copy the code
Methods :{} -> Data can also write methods in vue objects, but it is best to write methods in data objects
You can’t repeat that all data in methods and data will be stored on the VM, and that the names cannot conflict
<div v-on:click='fn'> </div>methods:{ fn:function(){ alert(this.a.name) }}
Copy the code
Pass event object
1. Write the parentheses fn() -> methods to retrieve the event object
Fn ($event,111) -> fn(event,number)
Event modifier
@click.stop -> Prevent event bubbling decorator.stop
@event. capture -> Event capture
@event. prevent -> Prevent default events
@ event. once -> Can only be triggered once
@event,self -> only triggered when you click on yourself
12. Use of Axios in Vue
Vue has a special method for sending Ajax requests that is called by the Created lifecycle hook function after the data is initialized, and this points to the VM instance
Download axios – >
npm install axios
Copy the code
Then the script tag is introduced
Axios spelled
created(){
axios.get('url').then((res)=>{
this.arr = res.data
})
}
Copy the code
Import axios from 'axios' // Set the default request prefix axios.defaults.baseURL = 'http://localhost:3000'; Axios. Interceptors. Response. Use (res = > {return res. The data / / unity interception result here. Process the results into res data}); Export let getSliders = () =>{return axios.get('/sliders')} // Get the popular book interface export let getHotBook = () =>{ return axios.get('/hot') }Copy the code
Where and where to import axios third-party modules directly into vue components. Official components need to be referenced in main.js
13. Promise fixes the callback problem
The traditional way of writing callback functions
function buy(callback){ setTimeout(function(){ let a = 'baicai'; callback(a); },2000)}buy(function(val){ console.log(val)})
Copy the code
Callback function: passes subsequent processing logic to the current task and is called when the task is done
Promise resolves the three promise states of the callback problem
- Successful state Resolve
- Failure state Reject
- Wait state pending
-
Resolve stands for successful transition state
-
Reject stands for reject state
-
Resolve and reject are both functions
An instance of a promise is a then method
The then method takes two parameters which are the two method parameters of the promise constructor and uses those two parameters in the promise to call the method in the THEN
Resolve calls then parameter one, reject calls then parameter two, which is already dead
let app = new Promise((resolve,reject) = >{ resolve('das') })app.then( (resolve) = >{},(reject) = >{})Copy the code
14. V-bind binding style
Adding the V-bind attribute to the DOM in the view binds the data attribute in the instance
<div v-bind:title='xx'></div>//Copy the code
V-bind can be abbreviated as: attribute name =”
<div :title='xx'></div>// same as aboveCopy the code
Use V-bind to bind CSS styles
The style of the class binding does not conflict with the class binding
1. Objects of the first type
X, y and z are definitionsclassStyle the <div class="x" :class="{z:true,y:flag1}"</div> </div>className:isActive} -> Determine this by specifying the isActive variableclassYou can also write whether to use it or notbooleanvalueCopy the code
2. The second way is array
<div class="x" :class="[class1,class2,{y:true}}]"</div>data:{class1:'x'.class2:'y'} give a variable a CSS class name in data, and then write it to the view through an array. Any variable or style that is written to the array will be used and defined will take effect if it's not defined it won't take effect or you can nest itCopy the code
Inline style
Object to write
<div style='font-size:30px; ' :style="{backgroundColor:red,color:'pink'}">
Copy the code
An array of writing
data:{ style1: {backgroundColor:red} style2:{color:pink}}<div :style="[style1,style2,{fontSize:'30px'}]"
Copy the code
15. The filter filter
Example filter, a collection object used to write filters
Custom method (toFixed) parameters of filter represents the pipe (|) the content of the right argument can pass parameters by calling the filter method
//vue instance filter:{toFixed(input,num){// this refers to window return input.tofixed (num); }} / / view in the view through the filter processing to display the data Equivalent to call this method for new return value {{item. ProductCount * item. ProductPrice | toFixed (2)}}Copy the code
In the view of using | toFixed will call the inside of the filter method does not change the original data Just change the view of the display effect
16.v-if v-show
V-if is the dom show is the style
If the DOM is toggled frequently use v-show and v-if as soon as the data is determined
V-if if false will not render the element and the elements within it
V-if can be used in conjunction with v-else
By default, the same structure will be reused when you switch dom and if you don’t reuse it you need to add a key
<div v-if='false' key='1'></div>
Copy the code
17. Vue animation
Vue animation can only be used if the DOM goes from show to hide, or hide to show
<transition> <div v-show="flag">demo</div></transition>
Copy the code
I then control this component to implement some animations and write those styles in CSS. V-xx controls all the Transition components
/ / to enter.v-enter{ opacity: 0; }// Enter the animation.v-enter-active{ transition: 1slinear; }// End the animation.v-leave-active{ opacity: 0; transition: 1slinear; }Copy the code
You can control each transition individually by adding a name attribute
<transition name='jw'> <div v-show="flag">demo</div> </transition>
Copy the code
.jw-enter{
opacity: 0;
}
.jw-enter-active{
transition: 1s linear;
}
.jw-leave-active{
opacity: 0; transition: 1s linear;
}
Copy the code
18. The animate. CSS animation library
NPM install animate. CSSCopy the code
The introduction of the animate. CSS
import 'animate.css'
Copy the code
The transition component then adds the entering and leaving animation properties. The property values must begin with animated using the animate class name
<transition enter-active-class="animated bounceInUp" leave-active-class="animated bounceOutDown"> <div V-show ="flag"> I love you </div> </transition>Copy the code
Transition can only be used on a single element, not multiple elements
Transition-group must be used to animate multiple elements with an index key to distinguish between different elements
V-for, by default, reuses the original DOM element and if it has a key and the key is different it thinks it’s two people
19.puted Computes attributes
Computed ‘attributes’ are not methods
1. Methods do not cache. Computed is cached based on attributes that depend on data managed by Vue that can change in response
2. The two parts consist of get and set(not just set). Normally, the set method is called when js assignments affect other people or form elements
3. If set is set and val is given to someone else, the current a will not be given a result
4. Cooperate with V-Model for data monitoring
5.computed Default call to get method must have return computed does not support asynchronous
6. To calculate a new value based on a change in value, use computed data for any complex computing logic
7. Data and other places write computed and can’t write anymore
Any internal changes in the data monitored by 8.computed will also trigger the listening methods, such as the data used by the methods in GET, and a change in the data will cause its own recalculation
9. Only changes in the data that affect the data will cause changes in the listening properties
Computed: {MSG () {} / / the default calling the get method} -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - / / object notation on you can customize the set getcomputed: {MSG: {the get () {}, the set () {}}} / / actual usage By listening on any data to return a new data computed objects are updated whenever the monitored data changes computed:{MSG (){return this.name+this.age; }}Copy the code
20
1. Observe changes in data. Perform one thing when the data changes
2. Asynchronous support is triggered only when values change otherwise we are better at using computed
3. The name of the watch property should be the same as the name of the person being observed
4. The disadvantage of watch is that it needs to monitor one attribute one by one
watch:{ a(newVal,oldVal){ setTimeout(() = >{ console.log(newVal) },200)}}Copy the code
Depth monitoring:
Watch can only monitor changes of one layer, so you need to enable in-depth monitoring
Default to function is equivalent to default to handler
Deep :true Indicates that the depth monitoring starts
Watch :{todos:{handler(){handler(){},deep:true}}Copy the code
21. The template tags
Vue provides us with a v-show that doesn’t have any practical meaning for wrapping elements. Template is not supported and only v-if can be used
<template v-if='true'></template>
Copy the code
You can bind a component by id
<template id='name'></template>-----------------let home = { template:'#name' }
Copy the code
22. The routing vue – the router
Routing: Access to different paths returns different results
Spa single page application
A way to achieve single-page development
-
Logging the jump path with a hash (which produces history management) will not cause 404 if the hash is not supported by SEO
-
The browser’s own history management method **history ** (history.pushstate ()) may cause a 404 error
-
If we use hash in development, we will use history
Install the vue – the router
npm i vue-router --save
Copy the code
1. Introduce the VueRouter class of vue-Router
const router = new VueRouter({ })
Copy the code
2. Configure a routing mapping table. Configure the relationship between paths and components
Let routes = [{path:'/a', Component :home}, -> path:'/a', Component :home}]Copy the code
3. Add the configuration information to the vue-router. Here, you can use an attribute to enable the history mode to jump to the router without using the hash mode
const router = new VueRouter({ routes,mode:'history' })
Copy the code
4. Add vue-Router to the instance
let vm = new Vue({ el:'#app' , router })
Copy the code
5. Finally use the router-view component in the view (this is the global component defined by vue-Router)
Router-view Displays the result of a route jump
<router-view></router-view>
Copy the code
Use router-link to manually redirect a route -> button declarative route redirect
<router-link to="/home" tag="button"> home </router-link> tag -> Specify route link style default is a tag styleCopy the code
Restyle router-Link **
- You can set class. Router-link-active in style
- The configuration parameter in the Vue-Router constructor changes the default style class name
const router = new VueRouter({ routes,linkActiveClass:'active' })
Copy the code
Route forward in JS mode
Once vue-Router instances are attached to the root component, each component has a property called ** Router ∗∗(any r is put into a method) and a property called ** ∗ Router **(any R is put into a method) There is also a property called **router∗∗(any r is put into a method) and **(any r is not put into a property).
$router.push('/list') // Forces the jump path this.$router.go(-1) // returns a level of this.$router.replace('/list') route to replace the current historyCopy the code
Routes configuration
{path:'*', Component :home}, // Display the default route {path:'*', Component :home}, // display the default route {path:'*', Component :home}, // display the default route {path:'*',component:home}, // display the default route {path:'*',component:home}, // display the default route {path:'*',component:home}, // redirect:'/home'}, // Path change components also switchCopy the code
The path parameter
Routes: {path:'/article/:c/:a', Component :article} ->/:a Path parameterCopy the code
Route. params∗∗: /article/2/d−> The actual vue will convert the parameters in the home directory into an object c:2,a: ‘d’ which will be placed on the instance route.params**: /article/2/d -> The actual vue will convert the arguments in the home directory to an object {c:2,a:’d’} that will be placed on the instance Route. params∗∗: The path input /article/2/d−> the actual vue will convert the parameters in the home directory to an object C :2,a: ‘d’, which will be placed on route.params on the instance
Template: ` < div > the {{$route. Params. C}} {{$route. Params. D}} article < / div > `, - > $route. Params. C | d can take to the parameters in the routingCopy the code
You can send Ajax via watch for today’s **$route** property changes, which are route parameter changes
$route(){}}Copy the code
Router-link Dynamically binds routing parameters
{path:'/detail/:bid',component:Detail,name:"detail"}, To route specified name Then bind dynamic parameters -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- : to = "{name: 'detail' params: {bid: book. BookId}}" by the name specified routing, Then bind routing parameters to ParamsCopy the code
Dynamic Routing Configuration
Components are automatically imported based on the hop of the route. You do not need to import components first
{ path:'/detail/:bid', component:()=>import('.. /components/Detail.vue'), name:"detail"}Copy the code
This method, a global hook, is executed each time before entering the route
Router. BeforeEach (function(to,from,next){}) -> Execute next() to go downCopy the code
Child route (Secondary route)
{path:' /detail', Component :detail, children:[// the path in children is never carried/if carried/indicates a level 1 route {path:'profile', Component :profile}, {path:'about',component:about} ]},Copy the code
In this case, the route is: /detail/profile
// The path in children is never carried/if carried /, it is a level 1 route
Configuration summary :**
- Create components
- Configure the routing
- Instantiation VueRouter
- Mount the routing
- Place the component
23. Custom instructions
Directives: The place in the Vue instance where the self-prescribed instructions are written
<button V-color ='flag'> color </button>Vue({directives:{color(EL,bandings):{// EL refers to a series of directives for this element that are accepted by the bandings of this element el.style.background = bingdings.value } }, data:{ flag:'red' }})Copy the code
24. Lifecycle hook functions
The life cycle
After loading the internal methods before beforeCreate creation,data and other methods are not needed
Created gets ajax initialization after creation
BeforeMount Before mounting data // Does this parameter make sense
Mounted After the dom operation, the real DOM rendering is complete
BeforeUpdate Data changes before data updates trigger this method
Update This method is triggered when the data Update is complete
The two methods for processing virtual DOM -> are generally replaced with Watch, which is triggered when all data changes
BeforeDestroy The timer can be cleared before the instance is destroyed, or the event binding can be cleared
Destroyed after the destruction of
The listener is removed after destruction
25. Methods on instances
- This.$data Specifies the data on the VM
- This $watch monitoring
- This.$el Specifies the element currently under control
- The value of this.$set is changed in response
- This.$options all attributes on the VM
- This.$nextTick() -> async method that waits for the DOM to complete
- This.$refs is the set of all refs. If the DOM element is not iterated through the v-for loop, only one dom element is iterated through the V-for loop
The ref attribute, if placed on a component and retrieved an instance of the component rather than a DOM element of the component, allows the parent component to use the child component
hide(){this.flag = false; } <son red='load'></son> ------------------- this.$refs.load.hide(); -> Calls the child component's methods by getting the instance's ref methodCopy the code
DOM rendering in VUE is asynchronous. If you want to obtain the content in the real DOM after data changes, you need to wait for the page to complete rendering. All DOM operations are best written in nextTick
26. The component
- Components replace traditional page development, improve development efficiency, facilitate reuse, facilitate collaborative development, and facilitate management and maintenance
- A component in VUE is a custom tag, and VUE treats it as a component, as long as it is not a w3c label
- Components are independent of each other and cannot cross component instances. Vm is also a component. Components have lifecycle functions within them
- Components that share data will be updated at the same time if they are independent
- Child components cannot directly use data from parent components (data interaction between components)
- Components can theoretically be nested indefinitely
Component classification
Functional division
- Page-level components A page is a component
- The base component pulls out the reusable parts
Component naming conventions
- Do not use – with uppercase multiple words in component names
- This is ok as long as the component name is the same as the definition name (the first letter can be capitalized)
- HTML uses a short line separating nomenclature, and THE hump in JS is also acceptable
Component classification
- Global components: You can declare that a local component is used anywhere at once: you must tell who this component belongs to->Global components are more commonly used when writing plug-ins
- The data in the component must be of function type, returning an instance as the component’s data
< my - handsome > < / my - handsome > -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Vue.com ponent (' my - handsome, {/ / an object can be thought of as a component Template :'<div> I am handsome </div>'})Copy the code
2. Trilogy used by local components:
- Create this component
- Register this component
- Referencing this component
< my - handsome > < / my handsome - > - > < my - handsome > as -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- let handsome = { Template :'<div> I am handsome </div>', data(){return obj}, methods: { fn(){ this.school = 'hello' } }, } let handsome1 = {template: '< div > I am very handsome < / div >'} -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- components: {' my - handsome, handsome, handsome1 }Copy the code
Direct parent-child data transfer:
Props property This property is a write property in an array that receives data passed by the parent component
You can pass it by binding when you use a subcomponent that is accepted by writing the corresponding data in the props array and then used in the template
<my-handsom :name='{{xxx}}'><my-handsome>
---------------
let handsom = { props:['name'],template:`<div>{{name}}</div>` }
Copy the code
However, the child component changes the data only when it accepts the data and does not affect the parent
Multiple components use the same data and the data changes the central view of multiple components
The parent component waits for the child component to complete the mount before starting the parent component
Parent component passes value to child component
1. Bind dynamic properties when the parent calls the child to pass method data and the parent object
<v-son :title='xxx'></v-son>
Copy the code
2. In the child component, props accepts data from the parent component
props:[]
- Attributes passed by the parent component will report an error if the child component and definition are used but the parent component’s attributes are used
Ref attribute passes a value
The parent component actively obtains the child component’s data and methods:
1. Define a ref when calling the child component
<v-son ref='xxx'></v-son>
Copy the code
2. Pass in the parent component
This.$refs.xxx. Property/methodCopy the code
The child component actively retrieves the parent component’s data and methods
This.$parent. Property/methodCopy the code
27. Publish and subscribe
A one-to-many design pattern -> Child components pass values to parent components
- Release emit
- Subscribe to on
The father binds some event and the son triggers the event and passes the parameter to the one-way data stream and the father refreshes the data and the son refreshes
$emit(‘child-msg’,800) this.$emit(‘child-msg’,800)
Parameter one is who I need to listen to and parameter two is what DATA I need to change
XXX =’ xx ‘-> The name of the property is to listen to the event that needs to be triggered. The value of the property is the event that needs to be done. The parameters of the child component will be accepted by the event as arguments
Son :{{title}} <button @click='getMoney()'>, methods: {{getMoney () enclosing $emit (' child - MSG, 800)}}} / / trigger your own custom events Let father method performs}}} - -- -- -- -- -- -- -- -- -- -- < son: title = 'money' @child-msg='things'></son>----------------------------vue->methods: {things(val){ this.money = 800 } },Copy the code
28. The slot
Normally if a component uses a closed tag in the parent component, it’s not going to show what’s inside the closed tag and if it does, it’s not going to show what’s inside the closed tag and then it’s going to show what’s inside the view
- Slots are used to customize templates
- There can be only one root element in a template that can be customized using element attributes
- Slot can put some default content and replace it if it is passed
- Tags without names are placed in default by default
The parent component writes in the closing tag. The child component uses slots in the template
< son > 123 < / son > -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- son: {template: ` < div > < slot > < / slot > < / div > `} -- -- -- -- -- -- -- -- -- -- so you can put 123 incoming to the divCopy the code
Specify slot by naming the slot ->slot = ‘XXX’
<modal>
<p slot='a'>123132</p><p slot='b'>6666</p>
</modal>
------------------------
<div>dialog <slot name='a'>
</slot><slot name='b'></slot>
</div>
Copy the code
Parent component methods are passed to child elements via slots
< modal > < p = 'a' slot @ click = 'fn' > 123132 < / p > < / modal > -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the fn is the parent component of the methods: {alert (1)} ------------------------- <div><slot name='a'> </slot></div>Copy the code
29. Labels delivered with vue
Template tag Component tag Transition tag Slot tag
Bind components dynamically using the Component tag and control them dynamically by binding is properties
<input type="radio" v-model="radio" value="home">home <input type="radio" v-model="radio" value="list">list<component : is = "radio" > < / component > - > is attribute to binding component - = -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- components: {} home, list ------------------------------- data() {return {modal:'modal',radio:'home' }}Copy the code
In this instance, two buttons can be selected to switch components, but these two components will be repeatedly destroyed and created, which is relatively high performance.
Created Mounted hooks are created by adding a keep-alive tag to the component so that it does not kill the component. Instead, a background cache is created by caching the component in preparation for future routes
<keep-alive> <component :is="radio"></component></keep-alive>
Copy the code
30.EventBus
Under normal circumstances, only the parent and the child can transmit directly to the ancestor. Although such operations can be carried out, it requires layer by layer uploading, which is still quite troublesome. Therefore, we provide an operation called EventBus, although we will use Vuex in the future
Normally the subcomponent emits an event and brother one listens for an event and brother two emits an event but there’s no way to listen to the subscription and the sibling element doesn’t listen for it so you need an object called EventBus to implement it and there’s a bug in the middle
Let EventBus = new Vue ({}) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- bor1created () {/ / to brother one plus listen for an event EventBus.$on('changedRed',(val)=>{ this.color = val; })},-----------------------bor2change(){EventBus.$emit('changedRed',this.old); }Copy the code
Non-parent components pass data (communication) -> EventBus
- Create a new JS file to import the vUE instantiate the VUE and expose the instance
- Introduce the instance just defined where you want to broadcast
- Via VueEmit.$emit(‘ name ‘,’ data ‘)
- Receive the data from vueememit.$on(‘ name ‘,function(){})
31. Install the vue – cli
NPM install vue-cli -g Global install vue-cliCopy the code
The project can then be initialized in any folder
Vue init webpackCopy the code
CD Project Name
NPM install Initializes the installation project without running it directly
npm run dev
32. The module
Node module specification CommonJS if reference import export for JS files
The CMD specification seaJS AMD specification requires the introduction of UMD in order to do compatibility processing
Esmodule -> How to define a module (a JS is a module)
Import {STR,str2,a} from'./a.js' // import {STR,str2,a} from' // import * as b from './a.js' // XXX from default import xx from './b.js' console.log(xx);Copy the code
33. Vue – CLI main.js explanation
Import Vue from 'Vue' // Vue runtime does not support template. // Vue = compiler + Runtime (compiler can compile templates) // Compiler has 6KCopy the code
And I’m just gonna go new Vue({]})
The function of the render function is to render the virtual DOM into the real DOM.
CreateElement returns the virtual DOM
new Vue({ render:function(createElement){ console.log( createElement('h1'.'hello')); return createElement('h1'.'hello'); }}).$mount('#app') -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- shorthandnew Vue({ render:(h) = >h('h1'['hello',h('span'.'A headline')])}).$mount('#app')
Copy the code
In vue-CLI, a. Vue file is a component
The structure of the component includes the Template Script style
<template></template><script> -> Export default {data(){-> },methods:{},computed:{}. Components :{}}</script><style scoped= "> ->scoped property makes this style only available to current files </style>Copy the code
Install vue-loader and rely on vue-template-compiler
Vue-loader parses the. Vue file of vue which is automatically called by the plugin below
Vue-template-compiler is used to parse VUE templates
npm i vue-loader vue-template-compiler --save-dev
Copy the code
Then configure it in webpack.config.js
{test:/\.vue$/,use:'vue-loader'}
Copy the code
If the NPM run dev package fails then it needs to be configured in config.js
const VueLoaderPlugin = require('vue-loader/lib/plugin')--------------------------plugins:[ new VueLoaderPlugin()]
Copy the code
The vue file introduced in main.js, which prints App out as an object,
We can use this object to replace the createElement object in the Render function for simple node rendering,
Hence the structure in the VUe-CLI template
import App from './App.vue'
render:(h) => h(App)
Copy the code
Vue-cli project structure
The root component will be placed in the SRC directory, usually App mian.js index.html
The page-level component creates a new folder called Page or Components
The base components will be placed in a folder called Base
Routes are also pulled out and placed in a folder
We only introduce one component (app.vue) in main.js(the root instance), and it will render this component into # App. All other components are introduced in this instance
It would be relatively cumbersome to introduce many components to implement paths in main.js, so we’ll pull the Router out
import Vue from 'vue';
// VUE is also needed here because modularity creates closures
import VueRouter from 'vue-router'
import Home from '.. /components/Home.vue'
import List from '.. /components/List.vue'
Vue.use(VueRouter)
export default new VueRouter({
routes:[
{path:'/home'.component:Home},
{path:'/list'.component:List},
]
})
-----------------------------
import router from './router'
Copy the code
When using vue-router, you need to use vue.use to import js files
Vue.use(VueRouter) // What is different is that to introduce vue-router, you must use use. Then Vue registers two global componentsCopy the code
35. Write vUE plug-ins
Import modal from './notify.vue' // import modal from './notify.vue' // Import modal from './notify.vue' // Import modal from '. // this.$notify({delay:1000}); notify.install = function(Vue,options={delay:3000}){ Vue.prototype.$notify = function(message,opt={}){ if(notify.el) return; if(document.body) options = {... options,... Opt} // override the default setting let V = vue.extend (modal) // Returns a subclass of the constructor whose arguments include the object selected by the component let vm = new V; let oDiv = document.createElement('div'); // create a div and mount the instance to the element vm.$mount(oDiv); vm.msg = message; document.body.appendChild(vm.$el); $el = vm.$el; SetTimeout () = > {/ / how many seconds delay The dom element to remove the document. The body. RemoveChild (vm) $el); // Delete notify.el = null; },options.delay); }} // Export the object containing install. If vue. use is used, the install method is called export default notify; - --------------------------- import notify from './plugin/notify.js' Vue.use(notify,{ delay:2000 }); // Use objects with installCopy the code