In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly shows you "Why this points to vue instances", which is easy to understand and clear. I hope it can help you solve your doubts. Let me lead you to study and learn this article "Why this points to vue instances".
Throw a question
Normal development of vue code, big or bad will be written like this
Export default {data () {return {name: 'Peng Yuyan'}}, methods: {greet () {console.log (`hello, I am ${this.name} `)}
Why can the this.name here directly access the name defined in data, or this.someFn can directly access the functions defined in methods? with this question, start to look at the source code of vue2.x to find the answer.
Source code analysis
Here first paste a vue source code address vue source code. Let's first take a look at the constructor of the vue instance. The constructor is in the directory of source code / vue/src/core/instance/index.js, and the amount of code is small. Post it all and have a look.
Function Vue (options) {if (process.env.NODE_ENV! = = 'production' & &! (this instanceof Vue)) {warn (' Vue is a constructor and should be called with the `new` keyword')} this._init (options)} initMixin (Vue) stateMixin (Vue) eventsMixin (Vue) lifecycleMixin (Vue) renderMixin (Vue) export default Vue
The constructor is very simple. If (! (this instanceof Vue)) {} determines whether the constructor is called with the new keyword. If not, warning is thrown. Here this refers to an instance of Vue. If you normally use the new keyword, then go to the _ init function, is not very simple.
_ init function analysis
Let uid = 0export function initMixin (Vue: Class) {Vue.prototype._init = function (options?: Object) {const vm: Component = this / / a uid vm._uid = uid++ let startTag EndTag / * istanbul ignore if * / if (process.env.NODE_ENV! = = 'production' & & config.performance & & mark) {startTag = `vue-perf-start:$ {vm._uid} `endTag = `vue-perf-end:$ {vm._uid}` mark (startTag)} / / a flag to avoid this being observed vm._isVue = true / / merge options if (options & & options._isComponent) {/ / optimize internal component instantiation / / since dynamic options merging is pretty slow And none of the / / internal component options needs special treatment. InitInternalComponent (vm, options)} else {vm.$options = mergeOptions (resolveConstructorOptions (vm.constructor), options | | {} Vm)} / * istanbul ignore else * / if (process.env.NODE_ENV! = = 'production') {initProxy (vm)} else {vm._renderProxy = vm} / / expose real self vm._self = vm initLifecycle (vm) initEvents (vm) initRender (vm) callHook (vm 'beforeCreate') initInjections (vm) / / resolve injections before data/props initState (vm) initProvide (vm) / / resolve provide after data/props callHook (vm,' created') / * istanbul ignore if * / if (process.env.NODE_ENV! = = 'production' & & config.performance & & mark) {vm._name = formatComponentName (vm, false) mark (endTag) measure (`vue ${vm._name} init`, startTag EndTag)} if (vm.$options.el) {vm.$mount (vm.$options.el)}
The _ init function is a bit long and has done a lot of things, so we won't interpret them one by one here. The content related to our exploration should be in the function initState (vm). Let's continue to have a look in the function initState.
InitState function analysis
Export function initState (vm: Component) {vm._watchers = [] const opts = vm.$options if (opts.props) initProps (vm, opts.props) if (opts.methods) initMethods (vm, opts.methods) if (opts.data) {initData (vm)} else {observe (vm._data = {}, true / * asRootData * /) if (opts.computed) initComputed (vm, opts.computed) if (opts.watch & & opts.watch! = nativeWatch) {initWatch (vm) Opts.watch)}}
You can see that initState did five things.
Initialize props
Initialize methods
Initialize data
Initialize computed
Initialize watch
Let's focus on what the initialization methods has done.
InitMethods initialization method
Function initMethods (vm, methods) {var props = vm.$options.props; for (var key in methods) {{if (typeof methods [key]! = 'function') {warn ("Method\"+ key +"\ "has type\") + (typeof methods [key]) + "\" in the component definition. "+" Did you reference the function correctly? ", vm);} if (props & & hasOwn (props, key)) {warn ((" Method\ "" + key + "\" has already been defined as a prop. "), vm) } if ((key in vm) & & isReserved (key)) {warn ("Method\"+ key +"\ "conflicts with an existing Vue instance method. "+" Avoid defining component methods that start with _ or $. ");}} vm [key] = typeof methods [key]! = 'function'? Noop: bind (methods [key], vm);}}
InitMethods is mainly based on some judgments:
To determine whether the function defined in methods is a function, throw warning; to determine whether the function name defined in methods conflicts with props, and throw warning; to judge whether the function name defined in methods conflicts with the function already defined on the Vue instance. If there is a conflict, developers are advised to start with _ or $.
Apart from the above judgment, the most important thing is to define all the methods in methods on the vue instance, and use the bind function to point the this of the function to the Vue instance, which is the instance object of our new Vue ().
This explains why this can access methods in methods directly.
InitData initialization data
Function initData (vm) {var data = vm.$options.data; data = vm._data = typeof data = = 'function'? GetData (data, vm): data | {}; if (! isPlainObject (data)) {data = {}; warn ('data functions should return an object:\ n' + 'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function', vm);} / / proxy data on instance var keys = Object.keys (data); var props = vm.$options.props Var methods = vm.$options.methods; var I = keys.length; while (iMuk -) {var key = keys [I]; {if (methods & & hasOwn (methods, key)) {warn (("Method\"+ key +"\ "has already been defined as a data property."), vm) }} if (props & & hasOwn (props, key)) {warn ("The data property\"+ key +"\ "is already declared as a prop. "+" Use prop default value instead. ", vm);} else if (! isReserved (key)) {proxy (vm," _ data ", key);} / / observe data observe (data, true / * asRootData * /);}
What does initdata do:
First assign a value to the instance _ data. The getData function processes the function of data and returns an object.
It is not the object that gives a warning to determine the data that is finally obtained.
Determine whether the function in methods conflicts with the key in data
Determine whether there is a conflict between props and key in data
Determine whether it is an internal private reserved attribute, if not, do a layer of proxy, proxy to _ data
Finally, monitor the data to make it responsive data.
Take a look at what the proxy function does:
Function noop (a, b, c) {} var sharedPropertyDefinition = {enumerable: true, configurable: true, get: noop, set: noop}; function proxy (target, sourceKey, key) {sharedPropertyDefinition.get = function proxyGetter () {return this [sourceKey] [key]}; sharedPropertyDefinition.set = function proxySetter (val) {this [sourceKey] [key] = val;}; Object.defineProperty (target, key, sharedPropertyDefinition);}
In fact, the Object.defineProperty here is used to define objects.
The purpose of proxy is to make this.name point to this._data.name.
The above is all the content of the article "Why this points to vue instances". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.