您好,登錄后才能下訂單哦!
今天小編給大家分享一下Vue2能通過(guò)this訪問(wèn)各種選項(xiàng)中屬性的原因是什么的相關(guān)知識(shí)點(diǎn),內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識(shí),所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來(lái)了解一下吧。
萬(wàn)事開(kāi)頭難,找到起點(diǎn)是最難的,對(duì)于前端項(xiàng)目,我們想要找到入口文件,一般都是從package.json
中的main
字段開(kāi)始找;
package.json
中的main
字段代表的是這個(gè)包的入口文件,通常我們可以通過(guò)這個(gè)字段的值來(lái)找到我們要閱讀的起點(diǎn)。
但是對(duì)于Vue
來(lái)說(shuō),這個(gè)字段是dist/vue.runtime.common.js
,這個(gè)文件是編譯后的文件,我們是看不懂的,所以需要找到源碼的入口文件;
這個(gè)時(shí)候我們就需要看package.json
中的scripts
字段:
{
"scripts": {
"dev": "rollup -w -c scripts/config.js --environment TARGET:full-dev",
"dev:cjs": "rollup -w -c scripts/config.js --environment TARGET:runtime-cjs-dev",
"dev:esm": "rollup -w -c scripts/config.js --environment TARGET:runtime-esm",
"dev:ssr": "rollup -w -c scripts/config.js --environment TARGET:server-renderer",
"dev:compiler": "rollup -w -c scripts/config.js --environment TARGET:compiler ",
"build": "node scripts/build.js",
"build:ssr": "npm run build -- runtime-cjs,server-renderer",
"build:types": "rimraf temp && tsc --declaration --emitDeclarationOnly --outDir temp && api-extractor run && api-extractor run -c packages/compiler-sfc/api-extractor.json",
"test": "npm run ts-check && npm run test:types && npm run test:unit && npm run test:e2e && npm run test:ssr && npm run test:sfc",
"test:unit": "vitest run test/unit",
"test:ssr": "npm run build:ssr && vitest run server-renderer",
"test:sfc": "vitest run compiler-sfc",
"test:e2e": "npm run build -- full-prod,server-renderer-basic && vitest run test/e2e",
"test:transition": "karma start test/transition/karma.conf.js",
"test:types": "npm run build:types && tsc -p ./types/tsconfig.json",
"format": "prettier --write --parser typescript "(src|test|packages|types)/**/*.ts"",
"ts-check": "tsc -p tsconfig.json --noEmit",
"ts-check:test": "tsc -p test/tsconfig.json --noEmit",
"bench:ssr": "npm run build:ssr && node benchmarks/ssr/renderToString.js && node benchmarks/ssr/renderToStream.js",
"release": "node scripts/release.js",
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s"
}
}
可以看到Vue
的package.json
中有很多的scripts
,這些相信大家都可以看得懂,這里我們只關(guān)注dev
和build
這兩個(gè)腳本;
dev
腳本是用來(lái)開(kāi)發(fā)的,build
腳本是用來(lái)打包的,我們可以看到dev
腳本中有一個(gè)TARGET
的環(huán)境變量,這個(gè)環(huán)境變量的值是full-dev
,我們可以在scripts/config.js
中找到這個(gè)值;
直接在scripts/config.js
中搜索full-dev
:
這樣就可以找到這個(gè)值對(duì)應(yīng)的配置:
var config = {
'full-dev': {
entry: resolve('web/entry-runtime-with-compiler.ts'),
dest: resolve('dist/vue.js'),
format: 'umd',
env: 'development',
alias: { he: './entity-decoder' },
banner
}
}
entry
字段就是我們要找的入口文件,這個(gè)文件就是Vue
的源碼入口文件,后面的值是web/entry-runtime-with-compiler.ts
,我們可以在web
目錄下找到這個(gè)文件;
但是并沒(méi)有在根目錄下找到web
目錄,這個(gè)時(shí)候我們就大膽猜測(cè),是不是有別名配置,這個(gè)時(shí)候我也正好在scripts
下看到了一個(gè)alias.js
文件,打開(kāi)這個(gè)文件,發(fā)現(xiàn)里面有一個(gè)web
的別名;
代碼如下:
module.exports = {
vue: resolve('src/platforms/web/entry-runtime-with-compiler'),
compiler: resolve('src/compiler'),
core: resolve('src/core'),
web: resolve('src/platforms/web'),
weex: resolve('src/platforms/weex'),
shared: resolve('src/shared')
}
為了驗(yàn)證我們的猜測(cè),我們可以在config.js
中搜一下alias
,發(fā)現(xiàn)確實(shí)有引入這個(gè)文件:
const aliases = require('./alias')
const resolve = p => {
const base = p.split('/')[0]
if (aliases[base]) {
return path.resolve(aliases[base], p.slice(base.length + 1))
} else {
return path.resolve(__dirname, '../', p)
}
}
再搜一下aliases
,發(fā)現(xiàn)確實(shí)有配置別名:
// 省略部分代碼
const config = {
plugins: [
alias({
entries: Object.assign({}, aliases, opts.alias)
}),
].concat(opts.plugins || []),
}
這樣我們就可以確認(rèn),web
就是src/platforms/web
這個(gè)目錄,我們可以在這個(gè)目錄下找到entry-runtime-with-compiler.ts
這個(gè)文件;
這樣我們就成功的找到了Vue
的源碼入口文件,接下來(lái)我們就可以開(kāi)始閱讀源碼了;
上面找到了入口文件,但是還是不知道如何閱讀源碼,這個(gè)時(shí)候我們就需要一些技巧了,這里我就分享一下我自己的閱讀源碼的技巧;
像我們現(xiàn)在看的源碼幾乎都是使用esm
模塊化或者commonjs
模塊化的,這些都會(huì)有一個(gè)export
或者module.exports
,我們可以通過(guò)這個(gè)來(lái)看導(dǎo)出了什么;
只看導(dǎo)出的內(nèi)容,其他的暫時(shí)不用管,直接找到最終導(dǎo)出的內(nèi)容,例如Vue
的源碼:
entry-runtime-with-compiler.ts
的導(dǎo)出內(nèi)容:
import Vue from './runtime-with-compiler'
export default Vue
這個(gè)時(shí)候就去找runtime-with-compiler.ts
的導(dǎo)出內(nèi)容:
runtime-with-compiler.ts
的導(dǎo)出內(nèi)容:
import Vue from './runtime/index'
export default Vue as GlobalAPI
這個(gè)時(shí)候就去找runtime/index.ts
的導(dǎo)出內(nèi)容:
runtime/index.ts
的導(dǎo)出內(nèi)容:
import Vue from 'core/index'
export default Vue
這個(gè)時(shí)候就去找core/index.ts
的導(dǎo)出內(nèi)容:
core/index.ts
的導(dǎo)出內(nèi)容:
import Vue from './instance/index'
export default Vue
這個(gè)時(shí)候就去找instance/index.ts
的導(dǎo)出內(nèi)容:
instance/index.ts
的導(dǎo)出內(nèi)容:
function Vue(options) {
if (__DEV__ && !(this instanceof Vue)) {
warn('Vue is a constructor and should be called with the `new` keyword')
}
this._init(options)
}
export default Vue as unknown as GlobalAPI
這樣我們就找到Vue
的構(gòu)造函數(shù)了,這個(gè)時(shí)候我們就可以開(kāi)始閱讀源碼了;
閱讀源碼的目的一定要清晰,當(dāng)然你可以說(shuō)目的就是了解Vue
的實(shí)現(xiàn)原理,但是這個(gè)目的太寬泛了,我們可以把目的細(xì)化一下,例如:
Vue
的生命周期是怎么實(shí)現(xiàn)的
Vue
的數(shù)據(jù)響應(yīng)式是怎么實(shí)現(xiàn)的
Vue
的模板編譯是怎么實(shí)現(xiàn)的
Vue
的組件化是怎么實(shí)現(xiàn)的
Vue
的插槽是怎么實(shí)現(xiàn)的
等等...
例如我們的這次閱讀計(jì)劃就是了解Vue
的this
為什么可以訪問(wèn)到選項(xiàng)中的各種屬性,這里再細(xì)分為:
Vue
的this
是怎么訪問(wèn)到data
的
Vue
的this
是怎么訪問(wèn)到methods
的
Vue
的this
是怎么訪問(wèn)到computed
的
Vue
的this
是怎么訪問(wèn)到props
的
上面順序不分先后,但是答案一定是在源碼中。
上面已經(jīng)找到了Vue
的入口文件,接下來(lái)我們就可以開(kāi)始閱讀源碼了,這里我就以Vue
的this
為什么可以訪問(wèn)到選項(xiàng)中的各種屬性為例,來(lái)分析Vue
的源碼;
首先看一下instance/index.ts
的源碼:
import { initMixin } from './init'
import { stateMixin } from './state'
import { renderMixin } from './render'
import { eventsMixin } from './events'
import { lifecycleMixin } from './lifecycle'
import { warn } from '../util/index'
import type { GlobalAPI } from 'types/global-api'
function Vue(options) {
if (__DEV__ && !(this instanceof Vue)) {
warn('Vue is a constructor and should be called with the `new` keyword')
}
this._init(options)
}
//@ts-expect-error Vue has function type
initMixin(Vue)
//@ts-expect-error Vue has function type
stateMixin(Vue)
//@ts-expect-error Vue has function type
eventsMixin(Vue)
//@ts-expect-error Vue has function type
lifecycleMixin(Vue)
//@ts-expect-error Vue has function type
renderMixin(Vue)
export default Vue as unknown as GlobalAPI
有這么多東西,我們不用管,要清晰目的,我們?cè)谑褂?code>Vue的時(shí)候,通常是下面這樣的:
const vm = new Vue({
data() {
return {
msg: 'hello world'
}
},
methods: {
say() {
console.log(this.msg)
}
}
});
vm.say();
也就是Vue
的構(gòu)造函數(shù)接收一個(gè)選項(xiàng)對(duì)象,這個(gè)選項(xiàng)對(duì)象中有data
和methods
;
我們要知道Vue
的this
為什么可以訪問(wèn)到data
和methods
,那么我們就要找到Vue
的構(gòu)造函數(shù)中是怎么把data
和methods
掛載到this
上的;
很明顯構(gòu)造函數(shù)只做了一件事,就是調(diào)用了this._init(options)
:
this._init(options)
那么我們就去找_init
方法,這個(gè)方法在哪我們不知道,但是繼續(xù)分析源碼,我們可以看到下面會(huì)執(zhí)行很多xxxMixin
的函數(shù),并且Vue
作為參數(shù)傳入:
//@ts-expect-error Vue has function type
initMixin(Vue)
//@ts-expect-error Vue has function type
stateMixin(Vue)
//@ts-expect-error Vue has function type
eventsMixin(Vue)
//@ts-expect-error Vue has function type
lifecycleMixin(Vue)
//@ts-expect-error Vue has function type
renderMixin(Vue)
盲猜一波,見(jiàn)名知意:
initMixin
:初始化混入
stateMixin
:狀態(tài)混入
eventsMixin
:事件混入
lifecycleMixin
:生命周期混入
renderMixin
:渲染混入
我們就去找這些混入的方法,一個(gè)一個(gè)的找,找到initMixin
,直接就找了_init
方法:
export function initMixin(Vue: typeof Component) {
Vue.prototype._init = function (options?: Record<string, any>) {
const vm: Component = this
// a uid
vm._uid = uid++
let startTag, endTag
/* istanbul ignore if */
if (__DEV__ && config.performance && mark) {
startTag = `vue-perf-start:${vm._uid}`
endTag = `vue-perf-end:${vm._uid}`
mark(startTag)
}
// a flag to mark this as a Vue instance without having to do instanceof
// check
vm._isVue = true
// avoid instances from being observed
vm.__v_skip = true
// effect scope
vm._scope = new EffectScope(true /* detached */)
vm._scope._vm = 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 as any)
} else {
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor as any),
options || {},
vm
)
}
/* istanbul ignore else */
if (__DEV__) {
initProxy(vm)
} else {
vm._renderProxy = vm
}
// expose real self
vm._self = vm
initLifecycle(vm)
initEvents(vm)
initRender(vm)
callHook(vm, 'beforeCreate', undefined, false /* setContext */)
initInjections(vm) // resolve injections before data/props
initState(vm)
initProvide(vm) // resolve provide after data/props
callHook(vm, 'created')
/* istanbul ignore if */
if (__DEV__ && 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)
}
}
}
代碼這么多沒(méi)必要全都看,記住我們的目的是找到data
和methods
是怎么掛載到this
上的;
先簡(jiǎn)化代碼,不看沒(méi)有意義的代碼:
export function initMixin(Vue) {
Vue.prototype._init = function (options) {
const vm = this
}
}
傳遞過(guò)來(lái)的Vue
并沒(méi)有做太多事情,只是把_init
方法掛載到了Vue.prototype
上;
在_init
方法中,vm
被賦值為this
,這里的this
就是Vue
的實(shí)例,也就是我們的vm
;
繼續(xù)往下看,我們有目的的看代碼,只需要看有vm
和options
組合出現(xiàn)的代碼,于是就看到了:
if (options && options._isComponent) {
initInternalComponent(vm, options)
} else {
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm
)
}
_isComponent
前面帶有_
,說(shuō)明是私有屬性,我們通過(guò)new Vue
創(chuàng)建的實(shí)例時(shí)走到現(xiàn)在是沒(méi)有這個(gè)屬性的,所以走到else
分支;
resolveConstructorOptions(vm.constructor)
中沒(méi)有傳遞options
,所以不看這個(gè)方法,直接看mergeOptions
:
export function mergeOptions(parent, child, vm) {
if (__DEV__) {
checkComponents(child)
}
if (isFunction(child)) {
// @ts-expect-error
child = child.options
}
normalizeProps(child, vm)
normalizeInject(child, vm)
normalizeDirectives(child)
// Apply extends and mixins on the child options,
// but only if it is a raw options object that isn't
// the result of another mergeOptions call.
// Only merged options has the _base property.
if (!child._base) {
if (child.extends) {
parent = mergeOptions(parent, child.extends, vm)
}
if (child.mixins) {
for (let i = 0, l = child.mixins.length; i < l; i++) {
parent = mergeOptions(parent, child.mixins[i], vm)
}
}
}
const options = {}
let key
for (key in parent) {
mergeField(key)
}
for (key in child) {
if (!hasOwn(parent, key)) {
mergeField(key)
}
}
function mergeField(key) {
const strat = strats[key] || defaultStrat
options[key] = strat(parent[key], child[key], vm, key)
}
return options
}
記住我們的目的,只需要關(guān)心vm
和options
組合出現(xiàn)的代碼,child
就是options
,vm
就是vm
,簡(jiǎn)化之后:
export function mergeOptions(parent, child, vm) {
normalizeProps(child, vm)
normalizeInject(child, vm)
normalizeDirectives(child)
return options
}
可以看到只剩下了normalizeProps
、normalizeInject
、normalizeDirectives
這三個(gè)方法,值得我們關(guān)注,但是見(jiàn)名知意,這三個(gè)方法可能并不是我們想要的,跟進(jìn)去看一眼也確實(shí)不是;
雖然沒(méi)有得到我們想要的,但是從這里我們也得到了一個(gè)重要信息,mergeOptions
最后會(huì)返回一個(gè)options
對(duì)象,這個(gè)對(duì)象就是我們的options
,最后被vm.$options
接收;
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm
)
現(xiàn)在我們分析要多一步了,參數(shù)只有vm
的函數(shù)也是需要引起我們的注意的,繼續(xù)往下看:
if (__DEV__) {
initProxy(vm)
} else {
vm._renderProxy = vm
}
操作了vm
,但是內(nèi)部沒(méi)有操作$options
,跳過(guò),繼續(xù)往下看:
initLifecycle(vm)
initEvents(vm)
initRender(vm)
callHook(vm, 'beforeCreate', undefined, false /* setContext */)
initInjections(vm) // resolve injections before data/props
initState(vm)
initProvide(vm) // resolve provide after data/props
callHook(vm, 'created')
initLifecycle
、initEvents
、initRender
、initInjections
、initState
、initProvide
這些方法都是操作vm
的;
盲猜一波:
initLifecycle
:初始化生命周期
initEvents
:初始化事件
initRender
:初始化渲染
initInjections
:初始化注入
initState
:初始化狀態(tài)
initProvide
:初始化依賴注入
callHook
:調(diào)用鉤子
這里面最有可能是我們想要的是initState
,跟進(jìn)去看一下:
export function initState(vm) {
const opts = vm.$options
if (opts.props) initProps(vm, opts.props)
// Composition API
initSetup(vm)
if (opts.methods) initMethods(vm, opts.methods)
if (opts.data) {
initData(vm)
} else {
const ob = observe((vm._data = {}))
ob && ob.vmCount++
}
if (opts.computed) initComputed(vm, opts.computed)
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch)
}
}
已經(jīng)找到我們想要的了,現(xiàn)在開(kāi)始正式分析initState
。
根據(jù)代碼結(jié)構(gòu)可以看到,initState
主要做了以下幾件事:
初始化props
初始化setup
初始化methods
初始化data
初始化computed
初始化watch
我們可以用this
來(lái)訪問(wèn)的屬性是props
、methods
、data
、computed
;
看到這里也明白了,為什么在props
中定義了一個(gè)屬性,在data
、methods
、computed
中就不能再定義了,因?yàn)?code>props是最先初始化的,后面的也是同理。
initProps
的作用是初始化props
,跟進(jìn)去看一下:
function initProps(vm, propsOptions) {
const propsData = vm.$options.propsData || {}
const props = (vm._props = shallowReactive({}))
// cache prop keys so that future props updates can iterate using Array
// instead of dynamic object key enumeration.
const keys = (vm.$options._propKeys = [])
const isRoot = !vm.$parent
// root instance props should be converted
if (!isRoot) {
toggleObserving(false)
}
for (const key in propsOptions) {
keys.push(key)
const value = validateProp(key, propsOptions, propsData, vm)
/* istanbul ignore else */
if (__DEV__) {
const hyphenatedKey = hyphenate(key)
if (
isReservedAttribute(hyphenatedKey) ||
config.isReservedAttr(hyphenatedKey)
) {
warn(
`"${hyphenatedKey}" is a reserved attribute and cannot be used as component prop.`,
vm
)
}
defineReactive(props, key, value, () => {
if (!isRoot && !isUpdatingChildComponent) {
warn(
`Avoid mutating a prop directly since the value will be ` +
`overwritten whenever the parent component re-renders. ` +
`Instead, use a data or computed property based on the prop's ` +
`value. Prop being mutated: "${key}"`,
vm
)
}
})
} else {
defineReactive(props, key, value)
}
// static props are already proxied on the component's prototype
// during Vue.extend(). We only need to proxy props defined at
// instantiation here.
if (!(key in vm)) {
proxy(vm, `_props`, key)
}
}
toggleObserving(true)
}
代碼很多,我們依然不用關(guān)心其他的代碼,只關(guān)心props
是怎么掛載到vm
上的,根據(jù)我上面的方法,簡(jiǎn)化后的代碼如下:
function initProps(vm, propsOptions) {
vm._props = shallowReactive({})
for (const key in propsOptions) {
const value = validateProp(key, propsOptions, propsData, vm)
if (!(key in vm)) {
proxy(vm, `_props`, key)
}
}
}
這里真正有關(guān)的就兩個(gè)地方:
validateProp
:看名字就知道是驗(yàn)證props
,跳過(guò)
proxy
:代理,很可疑,跟進(jìn)去看一下:
export 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)
}
這里的target
就是vm
,sourceKey
就是_props
,key
就是props
的屬性名;
這里通過(guò)Object.defineProperty
把vm
的屬性代理到_props
上,這樣就可以通過(guò)this
訪問(wèn)到props
了。
不是很好理解,那我們來(lái)自己就用這些代碼實(shí)現(xiàn)一下:
var options = {
props: {
name: {
type: String,
default: 'default name'
}
}
}
function Vue(options) {
const vm = this
initProps(vm, options.props)
}
function initProps(vm, propsOptions) {
vm._props = {}
for (const key in propsOptions) {
proxy(vm, `_props`, key)
}
}
function proxy(target, sourceKey, key) {
Object.defineProperty(target, key, {
get() {
return this[sourceKey][key]
},
set(val) {
this[sourceKey][key] = val
}
})
}
const vm = new Vue(options)
console.log(vm.name);
console.log(vm._props.name);
vm.name = 'name'
console.log(vm.name);
console.log(vm._props.name);
上面的代碼只是為了方便理解,所以會(huì)忽略一些細(xì)節(jié),比如
props
的驗(yàn)證等等,真實(shí)掛載在_props
上的props
是通過(guò)defineReactive
實(shí)現(xiàn)的,我這里直接是空的,這些超出了本文的范圍。
initMethods
的代碼如下:
function initMethods(vm, methods) {
const props = vm.$options.props
for (const key in methods) {
if (__DEV__) {
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)
}
}
跟著之前的思路,我們忽略無(wú)關(guān)代碼,簡(jiǎn)化后的代碼如下:
function initMethods(vm, methods) {
for (const key in methods) {
vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm)
}
}
這里的vm[key]
就是methods
的方法,這樣就可以通過(guò)this
訪問(wèn)到methods
中定義的方法了。
bind
的作用是把methods
中定義的函數(shù)的this
指向vm
,這樣就可以在methods
中使用this
就是vm
了。
簡(jiǎn)單的實(shí)現(xiàn)一下:
var options = {
methods: {
say() {
console.log('say');
}
}
}
function Vue(options) {
const vm = this
initMethods(vm, options.methods)
}
function initMethods(vm, methods) {
for (const key in methods) {
vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm)
}
}
function noop() {}
function polyfillBind(fn, ctx) {
function boundFn(a) {
const l = arguments.length
return l
? l > 1
? fn.apply(ctx, arguments)
: fn.call(ctx, a)
: fn.call(ctx)
}
boundFn._length = fn.length
return boundFn
}
function nativeBind(fn, ctx) {
return fn.bind(ctx)
}
const bind = Function.prototype.bind ? nativeBind : polyfillBind
const vm = new Vue(options)
vm.say()
initData
的代碼如下:
function initData(vm) {
let data = vm.$options.data
data = vm._data = isFunction(data) ? getData(data, vm) : data || {}
if (!isPlainObject(data)) {
data = {}
__DEV__ &&
warn(
'data functions should return an object:\n' +
'https://v2.vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
vm
)
}
// proxy data on instance
const keys = Object.keys(data)
const props = vm.$options.props
const methods = vm.$options.methods
let i = keys.length
while (i--) {
const key = keys[i]
if (__DEV__) {
if (methods && hasOwn(methods, key)) {
warn(`Method "${key}" has already been defined as a data property.`, vm)
}
}
if (props && hasOwn(props, key)) {
__DEV__ &&
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
const ob = observe(data)
ob && ob.vmCount++
}
簡(jiǎn)化之后的代碼如下:
function initData(vm) {
let data = vm.$options.data
// proxy data on instance
const keys = Object.keys(data)
let i = keys.length
while (i--) {
const key = keys[i]
proxy(vm, `_data`, key)
}
}
這里的實(shí)現(xiàn)方式和initProps
是一樣的,都是通過(guò)proxy
把data
中的屬性代理到vm
上。
注意:
initData
的獲取值的地方是其他的不相同,這里只做提醒,不做詳細(xì)分析。
initComputed
的代碼如下:
function initComputed(vm, computed) {
// $flow-disable-line
const watchers = (vm._computedWatchers = Object.create(null))
// computed properties are just getters during SSR
const isSSR = isServerRendering()
for (const key in computed) {
const userDef = computed[key]
const getter = isFunction(userDef) ? userDef : userDef.get
if (__DEV__ && getter == null) {
warn(`Getter is missing for computed property "${key}".`, vm)
}
if (!isSSR) {
// create internal watcher for the computed property.
watchers[key] = new Watcher(
vm,
getter || noop,
noop,
computedWatcherOptions
)
}
// component-defined computed properties are already defined on the
// component prototype. We only need to define computed properties defined
// at instantiation here.
if (!(key in vm)) {
defineComputed(vm, key, userDef)
} else if (__DEV__) {
if (key in vm.$data) {
warn(`The computed property "${key}" is already defined in data.`, vm)
} else if (vm.$options.props && key in vm.$options.props) {
warn(`The computed property "${key}" is already defined as a prop.`, vm)
} else if (vm.$options.methods && key in vm.$options.methods) {
warn(
`The computed property "${key}" is already defined as a method.`,
vm
)
}
}
}
}
簡(jiǎn)化之后的代碼如下:
function initComputed(vm, computed) {
for (const key in computed) {
const userDef = computed[key]
const getter = userDef
defineComputed(vm, key, userDef)
}
}
這里的實(shí)現(xiàn)主要是通過(guò)defineComputed
來(lái)定義computed
屬性,進(jìn)去瞅瞅:
export function defineComputed(target, key, userDef) {
const shouldCache = !isServerRendering()
if (isFunction(userDef)) {
sharedPropertyDefinition.get = shouldCache
? createComputedGetter(key)
: createGetterInvoker(userDef)
sharedPropertyDefinition.set = noop
} else {
sharedPropertyDefinition.get = userDef.get
? shouldCache && userDef.cache !== false
? createComputedGetter(key)
: createGetterInvoker(userDef.get)
: noop
sharedPropertyDefinition.set = userDef.set || noop
}
if (__DEV__ && sharedPropertyDefinition.set === noop) {
sharedPropertyDefinition.set = function () {
warn(
`Computed property "${key}" was assigned to but it has no setter.`,
this
)
}
}
Object.defineProperty(target, key, sharedPropertyDefinition)
}
仔細(xì)看下來(lái),其實(shí)實(shí)現(xiàn)方式還是和initProps
和initData
一樣,都是通過(guò)Object.defineProperty
來(lái)定義屬性;
不過(guò)里面的getter
和setter
是通過(guò)createComputedGetter
和createGetterInvoker
來(lái)創(chuàng)建的,這里不做過(guò)多分析。
上面我們已經(jīng)分析了props
、methods
、data
、computed
的屬性為什么可以直接通過(guò)this
來(lái)訪問(wèn),那么我們現(xiàn)在就來(lái)實(shí)現(xiàn)一下這個(gè)功能。
上面已經(jīng)簡(jiǎn)單了實(shí)現(xiàn)了initProps
、initMethods
,而initData
和initComputed
的實(shí)現(xiàn)方式和initProps
的方式一樣,所以我們直接復(fù)用就好了:
function Vue(options) {
this._init(options)
}
Vue.prototype._init = function (options) {
const vm = this
vm.$options = options
initState(vm)
}
function initState(vm) {
const opts = vm.$options
if (opts.props) initProps(vm, opts.props)
if (opts.methods) initMethods(vm, opts.methods)
if (opts.data) initData(vm)
if (opts.computed) initComputed(vm, opts.computed)
}
function initProps(vm, propsOptions) {
vm._props = {}
for (const key in propsOptions) {
vm._props[key] = propsOptions[key].default
proxy(vm, `_props`, key)
}
}
function proxy(target, sourceKey, key) {
Object.defineProperty(target, key, {
get() {
return this[sourceKey][key]
},
set(val) {
this[sourceKey][key] = val
}
})
}
function initMethods(vm, methods) {
for (const key in methods) {
vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm)
}
}
function noop() {}
function polyfillBind(fn, ctx) {
function boundFn(a) {
const l = arguments.length
return l
? l > 1
? fn.apply(ctx, arguments)
: fn.call(ctx, a)
: fn.call(ctx)
}
boundFn._length = fn.length
return boundFn
}
function nativeBind(fn, ctx) {
return fn.bind(ctx)
}
const bind = Function.prototype.bind ? nativeBind : polyfillBind
function initData(vm) {
vm._data = {}
for (const key in vm.$options.data) {
vm._data[key] = vm.$options.data[key]
proxy(vm, `_data`, key)
}
}
function initComputed(vm, computed) {
for (const key in computed) {
const userDef = computed[key]
const getter = userDef
defineComputed(vm, key, bind(userDef, vm))
}
}
function defineComputed(target, key, userDef) {
Object.defineProperty(target, key, {
get() {
return userDef()
},
})
}
const vm = new Vue({
props: {
a: {
type: String,
default: 'default'
}
},
data: {
b: 1
},
methods: {
c() {
console.log(this.b)
}
},
computed: {
d() {
return this.b + 1
}
}
})
console.log('props a: default',vm.a)
console.log('data b: 1', vm.b)
vm.c() // 1
console.log('computed d: 2', vm.d)
注意:上面的代碼對(duì)比于文章中寫(xiě)的示例有改動(dòng),主要是為了實(shí)現(xiàn)最后打印結(jié)果正確,增加了賦值操作。
以上就是“Vue2能通過(guò)this訪問(wèn)各種選項(xiàng)中屬性的原因是什么”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會(huì)為大家更新不同的知識(shí),如果還想學(xué)習(xí)更多的知識(shí),請(qǐng)關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。