Vue API knowledge points (2) -- options summary

Zhang Ning 187 2020-11-09 00:05:07
vue api knowledge points options


One 、 Options / data

1.data

When a component is defined ,data Must be declared as a function that returns an initial data object , Because components can be used to create multiple instances , If data It's still a broken object , Then all instances will be shared to refer to the same data object . By providing data function , After each new instance is created , We can call data function , Returns a new copy of the original data .

 

2.props

props It can be an array or an object , Used to receive data from the parent component .props Advanced options can be configured using objects in , Type detection , Custom validation , Set the default value

You can use the following options

type: Can be one of the native constructors :String、Number、Boolean、Array、Object、Date、Function、Symbol、 Any custom constructor , Or an array of the above . One will check prop Whether it's a given type , Otherwise, a warning will be thrown out .

default: by prop Specify a default value . If it's time to prop Not passed in , Use this value instead . The default value of an object or array must be returned from a factory function

required:Boolean Define the prop Is it required

validator:function The custom validation function will prop The value of is carried in as a unique parameter . return false Just give the default value , There's a warning on the console

 props: {
 // Detection type 
 height: Number,
 // Detection type + Other validation 
 age: {
type: Number,
 default: 0,
required: true,
validator: function (value) {
 return value >= 0
}
}
}

 

3.propsData

Used only for new In the instance created , Pass props, The main function is to facilitate testing ( In the process of development, you can hardly use )

 

4.computed  Compute properties

Calculated properties will be mixed into Vue In the example , all geter and setter Of this The context is automatically bound to Vue example

Note that if you use the arrow function for a computed property , be this Does not point to an instance of this component , However, you can still access the instance as the first parameter of the function .

The results of the calculated properties are cached , Unless you rely on the response property Change will recalculate . Be careful , If a dependency ( It has to be nonresponsive property) Outside the scope of this example , The calculated properties are not updated .

 <p>a + b The result is :{{ count }}</p>
 computed: {
count(){
return this.a + this.b
}
}

Compute properties vs Method

 <p>a + b The result is :{{ count() }}</p>
 methods: {
count(){
return this.a + this.b
}
}

We can define the same function as a method instead of a calculated property , The end result of the two ways is exactly the same . The difference is Computed properties are cached based on their responsive dependencies . They recalculate the evaluation only if the corresponding responsive dependency changes . That is, as long as a perhaps b It hasn't changed , Multiple access count The calculated property will immediately return the previous calculation result , Instead of executing the function again .

by comparison , Whenever re rendering is triggered , Call method will always execute function again ,

Why do we need caching ? Let's say we have a computing property with high performance overhead A, He needs to traverse a huge array and do a lot of computation , Then we may have other computational properties that depend on A. Without caching, we will inevitably execute many times A Of getter. If you don't want a cache to appear , Please use the method instead of .

Computed attribute setter

The default calculation property is getter , But you can also provide one when needed setter

 computed: {
str: {
get: function() {
return this.a + this.b
},
set: function(newVlaue) {
var abs = newValue.split(' ')
this.a = abs[0]
this.b = abs[abs.length - 1]
}
}
}

Now run this.str = '2 3 4 5' when ,setter Will be called ,this.a and this.b Will also be updated accordingly

5.methods Event handling

Pass in template v-on Define the method name , stay methods Method defined in

Sometimes the original... Is accessed in the inline statement processor DOM event , You can use special variables $event Put it into the method

<button @click="count(200, $event)"> Button </button>
<button @click="count2"> Button 2</button>
 methods: {
count: function(val, event) {
if(event) {
event.preventDefault()
}
// ...
 },
count2: function(event) {// If nothing is passed in the template , Here, you can accept a parameter directly by default, that is dom object 
if(event) {
event.preventDefault()
}
// ...
 }
}

6.watch Monitor

An object , A bond is an expression that needs to be observed , Value is the corresponding callback function , Value can also be method name , Or objects with options .Vue Instance will call... At instantiation time $watch(), Traverse watch Every attribute of an object

Values are objects that include options , There are three options

handler: Callback function , That is, the function that should be executed when monitoring changes

deep: Boolean, Make sure you're listening in depth

In order to find changes in the internal value of an object , Can be specified in option parameters deep: true Note that you don't need to do this for listening to array changes

immediate:Boolean, by true when , The callback will immediately start with the current value of the expression ( Enter the page and start listening )

 watch: {
a(){},
// The callback will be on any object that is monitored property Called when changed , No matter how deep it's nested 
 b: {
handler: function(){},
deep: true
},
// The callback will be called immediately after the start of listening 
 c: {
handler: function(),
immediate: true
},
// You can pass in the callback array , They will be called one by one 
 d: [
handle1,
function handle2(){},
{
handler: function handle3(){}
}
]
}

 

Two 、 Options / DOM

These things are rarely considered in the development process , Take a look at the official website to get familiar with

Go to the official website to find out

  3、 ... and 、 Options / Lifecycle hook

Every Vue Instances are created through a series of initialization processes , Set up data listening , Compiling templates , The instance is attached to DOM , Update when data changes DOM etc. , There's a series of functions , It's called a life cycle hook

1.beforeCreate

After the instance is initialized , The data observed (data observer) and event/watcher The event configuration is called before , At this time, the option object of the component has not been created ,el and data Not initialized , So there's no access to methods,data,computed The method and data of etc

 

2.created

It is called immediately after the instance creation . This step , The instance has completed the following configuration : The data observed (data observer),property And method operations ,watch/event Event callback . However, the mount phase has not yet started ,$el property Not yet available . This is a common life cycle , You can call methods The method in , change data Data in , And modification can be done by vue The responsive binding is reflected on the page , obtain Compute properties wait , Usually we request data from the interface here ,

 

3.beforeMount

Called before hanging on , dependent render The function is called for the first time , The instance has completed the following configuration : Compiling templates , hold data Data and template generation inside html, It's done el and data initialization , Note that it has not been mounted to html On the page

 

4.mounted

The instance is called after it is mounted , At this time el Newly created vm.$el To replace the . If the instance is mounted to an element in a document , When mounted When called vm.$el Also in the document

Be careful mounted There is no guarantee that all the child components will be mounted together , If you want to wait until the entire view is rendered , Can be in mounted For internal use vm.$nextTick 

 mounted(){
this.$nextTick(function(){
// ...
})
}

 

5.beforeUpdate

Call... When data is updated , It happens in the virtual DOM Before patching , This is a good place to access existing DOM, For example, remove the added event listener manually .

This hook is not called during server-side rendering , Because only the first rendering will be done on the server

 

6.updated

Virtual due to data changes DOM Re rendering and patching , The hook is called after this .

When the hook is called , Components DOM Has been updated , So you can now execute depending on DOM The operation of . But most of the time , You should avoid changing state during this period . If you want to change the state accordingly , It's usually best to use Compute properties or watcher Instead, .

Be careful updated There is no guarantee that all sub components will be redrawn together . If you want to wait until the entire view is redrawn , Can be in updated Use in vm.$nextTick( ditto )

 

 7.activated

By keep-alive Called when the cached component is activated

This hook is not called during server-side rendering

 

8.deactivated

By keep-alive The cached component is called when it is deactivated

This hook is not called during server-side rendering

 

9.beforeDestroy

Call before instance destruction . In this step , Instance is still fully available

This hook is not called during server-side rendering

 

10.destroyed

Call after instance destruction , After the hook is called , Corresponding Vue All instructions of the instance are unbound , All event listeners are removed , All the sub instances are destroyed

This hook is not called during server-side rendering

 

11.errorCaptured

Called when an error is caught from a descendant component , This hook will receive three parameters : Error object 、 The component instance where the error occurred and a string containing information about the source of the error . This hook returns false To prevent the error from continuing to propagate upward

You can modify the state of a component in this hook . So when catching errors , It's important to have a conditional judgment in the template or render function to bypass the rest , Otherwise, the component may enter an infinite rendering cycle

Error propagation rules

1. By default , If the overall situation is config.errorHandler Defined , All errors will still send it , So these errors are still reported to a single analysis service .

2. If there are more than one in the inheritance or parent subordinate link of a composition errorCaptured hook , Then they will be aroused by the same mistakes

3. If so errorCaptured The hook itself threw an error , The new error and the error that was caught will be sent to the global config.errorHandler

4. One errorCaptured The hook can return false To prevent the error from spreading upward . In essence, it means ’ This error has been fixed and should be ignored ‘. He will stop anything else that will be aroused by this mistake errorCaptured Hook and global config.errorHandler

 

Four 、 Options / resources

1.directives Custom instruction

2.filters filter

3.components Components

directives、filters、components The details are introduced here  vue API Knowledge point (1)--- overall situation API summary

 

5、 ... and 、 Options / Combine

1.parent

Specifies the parent instance of the created instance , Establish a parent-child relationship between the two . Sub instances can be used this.$parent Access parent instance , The child instance is pushed into the parent instance's $children Array

We are in development , Basically, it won't use $parent and $children . It's more about use props and events Implement parent-child component communication ,

 

2.mixins Mix in

3.extends

Allow declaration to extend another component , Without having to use Vue.extend. This is mainly to facilitate the extension of single file components

This sum mixins It's kind of similar

mixins、extends There is a detailed introduction in this article   vue API Knowledge point (1)--- overall situation API summary

 

4.provide / inject 

provide and inject Mainly in the development of high-level plug-ins / When using component library . It is not recommended for normal application code .

This pair of options need to be used together , To allow an ancestor component to inject a dependency into all its descendants , No matter how deep the component level is , And it will take effect all the time when the upstream downstream relationship is established .

analysis : There are too many levels of component introduction , Our descendant component wants to obtain the resources of the ancestor component , May not be used props In turn, it is passed on to the descendant components in turn , There are too many levels , Code structure is easy to be confused . Then you can use it provide/inject To deliver

Official annotation

provide Option should be an object or a function that returns an object . This object contains... That can be injected into its descendants property. You can use... In this object Symbols As key, But only in native support Symbol and Reflect.ownKeys Working in an environment of

inject The option should be an array of strings or an object , Object's key Is the local binding name ,

value yes Search the available injected content for key( String or Symbol), Or an object , The object

from property It's used for searching in available things such as content key( String or Symbol)

  default property It's used in degraded situations value

Personal analysis

provide It's an object , Or a function that returns an object , It contains things for future generations , That is, attributes and attribute values

inject An array of strings , Or an object . Property value can be an object , contain from and default The default value is

 const Child = {
inject: {
foo: {
from: 'bar',
default: 'foo'
}
}
}

from Indicates that the key,default The default, of course

  Be careful :provide and inject Binding is not responsive . This is intentional , However , If you pass in a listener object , So the object of property Still responsive

  The official sample

 // Parent component 
var Provider = {
provide: {
name: 'zhangning'
},
// ...
 }
// Subcomponent injection 
var Child = {
inject: ['name'],
created() {
console.log(this.name) // => 'zhangning'
 }
}

utilize es Medium Symbols、 function provide And the object inject

 const a = Symbol();
const Parent = {
provide(){
return {
[a]: 'zhangning187'
}
}
}
const Child = {
inject: { a },
// ...
}

In the new version , Use an injected value as a property The default value of

 const Child = {
inject: ['name'],
props: {
bar: {
default() {
return this.name
}
}
}
}

Use an injected value as the data entry

 const Child = {
inject: ['name'],
data() {
return {
bar: this.name
}
}
}

If it needs to be from a different name property Inject , Then use from To show its source property

 const Child = {
inject: {
from: 'bar',
default: 'name'
}
}

And prop The default value of is similar to , You need to use a factory method for non raw values

 const Child = {
inject: {
name: {
from: 'bar',
default: () => [1, 2, 3]
}
}
}

  In daily development , We often use Vuex Do state management , however vuex Sometimes it's too complicated . If we don't want to use vuex, At this time we can use provide/inject This way to replace vuex, Pass in the variable in the following component , Then it can be used in the descendant component

// Provide a non responsive variable in the following component to the descendant component

 export default {
provide() {
return {
text: 'zhangning'
}
}
}
// Descendant component injection 
export default {
inject: ['text'],
created() {
this.text = 'zhangning187'// When we use text When it's still zhangning, instead of zhangning187
 }
}

It's already said ,provide and inject Binding is not responsive , This can be done for . Of course, we can also pass in a responsive object , Then its properties are responsive

in other words ,Vue It won't be right provide The variables in are processed in a reactive way . So think about inject The accepted variables are reactive ,provide The supplied variable itself needs to be responsive .

Because the various states inside the component are responsive , So we inject the component itself directly into the root component provide, here , We can access all the states in the root component freely in the descendant component , The root component becomes the container of the global state

 // The root component provides itself to the descendant component 
export default {
provide() {
return {
app: this
}
},
data() {
return {
text: 'zhangning'
}
}
}
// Descendant components Inject 

export default {
inject: ['app'],
data(){
return{}
},
created: {
this.app.text = 'zhangning187'// At this time to use text, Its value is zhangning187
 }
}

Of course , We can also pass $root To get the root node , But in the process of team development , If all global variables are uniformly defined in the root component, it is not appropriate , While using provide/inject The entrance components of different modules can be passed to their offspring components to solve this problem perfectly

Vuex and provide/inject The difference lies in ,Vuex Every change to the global state in is traceable , and provide/inject The modification of variables in is out of control , Generally speaking, it means , You don't know which component modified the global state .

provide/inject Breaking our one-way data flow principle . If multiple descendant components simultaneously depend on the state provided by one ancestor component , So as long as one component changes the State , Then all components will be affected . This increases the coupling , Let our data change uncontrollable , In the process of multi person development , This can become particularly confusing .

The above seems to use provide/inject It seems very dangerous to do global state management , So we have to be careful with this approach .

But when it comes to component development ,vue The official advocates that we use this method . for example elment-ui 

 

6、 ... and 、 Options / other

1.name

Only works as a component option

Allow component templates to call themselves recursively , Be careful , Components are used globally Vue.component() Registration time , overall situation ID Automatically as a component of name

Appoint name The advantage of the option is that it's easy to debug , Named components have more friendly warning messages , When in vue-devtools Next , Unnamed components will be displayed as <AnonymousComponent>, It's very semantic , By providing name Options , You can get a component tree with more semantic information

 

2.delimiters

Just get to know , You don't usually change the insertion separator

type Array<string>

The default value is ["{{", "}}"]

Limit This option is only available when compiling in browsers in full builds

Change plain text insert separator

Example

 new Vue({
delimiters: ["${", "}"]
})
// The separator becomes ES6 Template string style 

 

3.functional

Get to know , It's not usually used

type Boolean

Make the component group state ( No, data) And there is no instance ( No, this Context ). They use a simple one render Function returns the virtual node , It's their rendering that costs less

 

4.model

Allow a custom component to use v-model Time to customize prop and event. By default , On a component v-model Will be able to value Used as a prop And input Used as a event, But the following input types, such as radio and check box buttons, may want to use value prop To achieve different purposes . Use model Options can avoid conflicts that arise from these situations

// Define a component

 Vue.component('my-check', {
model: {
prop: 'checked',
event: 'change'
},
props: {
value: String,
checked: {
type: Number,
default: 0
}
}
})

Use

 <my-check v-model='foo' value='some value'></my-check>

The above code is equivalent to

 <my-check :checked='foo' @change='value=>{foo = val}' value='some value'></my-check>

Let's get to know input Medium v-model How to realize bidirectional binding .

 <input type='text' v-model='msg'>

v-model It's just the real way to realize grammar sugar

 <input type='text' :value='msg' @input='msg=$event.target.value'>

The real two-way binding is through listening input event

v-model Internally, different attributes are used for different input elements and different events are thrown

text and textarea Element usage value Properties and input event

checkbox and radio Use checked Properties and change event

select Use value and change event

We can customize the input box component of v-model, Two way binding

 Vue.component('my-input', {
template: `<input :value='value' @input='updateValue($event.target.value)' type='text'></input>`,
props: ['value'],
methods: {
updateValue(val) {
this.$emit('input', val)
}
}
})
let app = new Vue({
el: '#app',
data(){
message: ''
},
methods: {
handleInput(val) {
this.message = val
}
}
})
 <div id='app'>
<my-input :value='message' @input='handleInput'></my-input>
</div>

From the example above, we can see that , By default , On a component v-model Will be able to value Used as a prop And input Used as a event, So when we're in a Use... On custom components v-model It doesn't implement two-way binding , Because custom components don't have default value and input event , When use , We need to explicitly define these things as above , At this time , Options model That comes in handy , Specify when defining a component prop The value of and the event to listen to ( See here , The example given on the official website above should also be able to see clearly )

give an example

 Vue.component('my-input', {
model: {
prop: 'uname',
event: 'handleChange'
},
props: {
uname: {
type: String,
default: 'zhangning'
}
},
methods: {
updateVal(val) {
this.$emit('handleChange', val)
}
}
})

Templates

 <template>
<div>
<input type='text' :value='uname' @input='updateVal($event.target.value)'>
</div>
</template>

Use components

 <my-input v-model='name' value='some value'></my-input>

Equivalent to

 <my-input :uname='name' @handleChange='val=>{foo = val}' value='some value'></my-input>

In the example above, we can use v-model To do two-way binding ( Take a look at the examples to see )

 

版权声明
本文为[Zhang Ning 187]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple