Analyze the principle of Vue2 implementing composition API
Jan 13, 2023 am 08:30 AMSince the release of Vue3
, the word composition API
has come into the vision of students who write Vue
, I believe Everyone has always heard that the composition API
is much better than the previous options API
. Now due to the release of the @vue/composition-api
plug-in, Vue2
students can also get on board. Next, we will mainly use the responsive ref
and reactive
to conduct an in-depth analysis of how this plug-in implements this function.
How to use
// 入口文件引入并注冊 import Vue from 'vue' import VueCompositionAPI from '@vue/composition-api' Vue.use(VueCompositionAPI)
// vue文件使用 import { defineComponent, ref, reactive } from '@vue/composition-api' export default defineComponent({ setup () { const foo = ref('foo'); const obj = reactive({ bar: 'bar' }); return { foo, obj } } })
How about it? After reading it, do you feel exactly the same as vue3
? You may think:
This is
vue2
Ah, my previousdata
andmethods
also have variables and methods in them, how can I do it the same assetup
The return values ??are merged together. [Related recommendations: vuejs video tutorial, web front-end development]vue2
is not only defined inWill the data in data
be processed responsively? How doref
andreactive
do it?vue2
Constraints defined by responsive data (add attributes that are not assigned to the original object, modify array subscripts, etc.), useref
instead Is it okay withreactive
?
Of course there are still a lot of doubts, because the plug-in provides quite a lot of API
, covering most of what Vue3
has, here Let’s analyze how it is done mainly from these questions.
Principle Analysis
Thanks to Vue
’s plug-in system, @vue/composition-api
is like vue-router
and vuex
are also injected through officially provided plug-ins.
// 這里只貼跟本章要講的相關(guān)代碼 funciton mixin (Vue) { Vue.mixin({ beforeCreate: functionApiInit } } function install (Vue) { mixin(Vue); } export const Plugin = { install: (Vue: VueConstructor) => install(Vue), }
Vue
The plug-in exposes a install
method to the outside. When use
is called, this method will be called and Vue
The constructor is passed in as a parameter, and then Vue.mixin
is called to handle the function when mixing in the corresponding hook.
The next step is to look at what functionApiInit
does
function functionApiInit(this: ComponentInstance) { const vm = this const $options = vm.$options const { setup, render } = $options // render 相關(guān) const { data } = $options $options.data = function wrappedData() { initSetup(vm, vm.$props) return isFunction(data) ? ( data as (this: ComponentInstance, x: ComponentInstance) => object ).call(vm, vm) : data || {} }
because Vue
is in beforeCreated
and created
During the life cycle, the data will be processed by initState
. When processing data
, $options.data
will be called to obtain the defined data. , so the function is re-wrapped here. This is one of the reasons why beforeCreate
hook injection is chosen. It must be wrapped before the function is called.
Next, let’s see what initSetup
does
function initSetup(vm: ComponentInstance, props: Record<any, any> = {}) { const setup = vm.$options.setup! const ctx = createSetupContext(vm) const instance = toVue3ComponentInstance(vm) instance.setupContext = ctx def(props, '__ob__', createObserver()) resolveScopedSlots(vm, ctx.slots) let binding: ReturnType<SetupFunction<Data, Data>> | undefined | null activateCurrentInstance(instance, () => { binding = setup(props, ctx) }) // setup返回是函數(shù)的情況 需要重寫render函數(shù) const bindingObj = binding Object.keys(bindingObj).forEach((name) => { let bindingValue: any = bindingObj[name] // 數(shù)據(jù)處理 asVmProperty(vm, name, bindingValue) }) return } }
This function is relatively long, and the code logic that is not on the main line to be explained this time has been deleted. This function mainly creates ctx
and convert the vm
instance into the instance
defined by the Vue3
data type, then execute the setup
function to get the return value, and then traverse For each property, call asVmProperty
to mount it on vm
. Of course, the mounting here is not by directly adding the properties and values ??to vm
. Doing so will There is a problem, that is, subsequent modifications to this attribute cannot be synchronized to vm
. The most common data proxy of Vue
is used here.
export function asVmProperty( vm: ComponentInstance, propName: string, propValue: Ref<unknown> ) { const props = vm.$options.props if (!(propName in vm) && !(props && hasOwn(props, propName))) { if (isRef(propValue)) { proxy(vm, propName, { get: () => propValue.value, set: (val: unknown) => { propValue.value = val }, }) } else { proxy(vm, propName, { get: () => { if (isReactive(propValue)) { ;(propValue as any).__ob__.dep.depend() } return propValue }, set: (val: any) => { propValue = val }, }) } }
Seeing this, I believe you have understood why the returned value defined in setup
can be used in template
, data
, methods
etc., because the returned things have been proxied to vm
.
Responsiveness (ref
reactive
implementation)
Next let’s talk about responsiveness and why ref
and reactive
can also make data reactive. The implementation of
ref
is actually a re-encapsulation of reactive
, mainly used for basic types.
function ref(raw?: unknown) { if (isRef(raw)) { return raw } const value = reactive({ [RefKey]: raw }) return createRef({ get: () => value[RefKey] as any, set: (v) => ((value[RefKey] as any) = v), }) }
Because reactive
must accept an object, so a constant is used here as the key
of ref
, which is
const value = reactive({ "composition-api.refKey": row })
export function createRef<T>( options: RefOption<T>, isReadonly = false, isComputed = false ): RefImpl<T> { const r = new RefImpl<T>(options) const sealed = Object.seal(r) if (isReadonly) readonlySet.set(sealed, true) return sealed } export class RefImpl<T> implements Ref<T> { readonly [_refBrand]!: true public value!: T constructor({ get, set }: RefOption<T>) { proxy(this, 'value', { get, set, }) } }
通過 new RefImpl
實(shí)例,該實(shí)例上有一個(gè) value
的屬性,對 value
做代理,當(dāng)取值的時(shí)候返回 value[RefKey]
,賦值的時(shí)候賦值給 value[RefKey]
, 這就是為什么 ref
可以用在基本類型,然后對返回值的 .value
進(jìn)行操作。調(diào)用 object.seal
是把對象密封起來(會(huì)讓這個(gè)對象變的不能添加新屬性,且所有已有屬性會(huì)變的不可配置。屬性不可配置的效果就是屬性變的不可刪除,以及一個(gè)數(shù)據(jù)屬性不能被重新定義成為訪問器屬性,或者反之。但屬性的值仍然可以修改。)
我們主要看下 reactive
的實(shí)現(xiàn)
export function reactive<T extends object>(obj: T): UnwrapRef<T> { const observed = observe(obj) setupAccessControl(observed) return observed as UnwrapRef<T> } export function observe<T>(obj: T): T { const Vue = getRegisteredVueOrDefault() let observed: T if (Vue.observable) { observed = Vue.observable(obj) } else { const vm = defineComponentInstance(Vue, { data: { $$state: obj, }, }) observed = vm._data.$$state } return observed }
我們通過 ref
或者 reactive
定義的數(shù)據(jù),最終還是通過了變成了一個(gè) observed
實(shí)例對象,也就是 Vue2
在對 data
進(jìn)行處理時(shí),會(huì)調(diào)用 observe
返回的一樣,這里在 Vue2.6+
把observe
函數(shù)向外暴露為 Vue.observable
,如果是低版本的話,可以通過重新 new
一個(gè) vue
實(shí)例,借助 data
也可以返回一個(gè) observed
實(shí)例,如上述代碼。
因?yàn)樵?reactive
中定義的數(shù)據(jù),就如你在 data
中定義的數(shù)據(jù)一樣,都是在操作返回的 observed
,當(dāng)你取值的時(shí)候,會(huì)觸發(fā) getter
進(jìn)行依賴收集,賦值時(shí)會(huì)調(diào)用 setter
去派發(fā)更新,
只是定義在 setup
中,結(jié)合之前講到的 setup
部分,比如當(dāng)我們在 template
中訪問一個(gè)變量的值時(shí),vm.foo
-> proxy
到 setup
里面的 foo
-> observed
的 foo
,完成取值的流程,這會(huì)比直接在 data
上多代理了一層,因此整個(gè)過程也會(huì)有額外的性能開銷。
因此使用該 API
也不會(huì)讓你可以直接規(guī)避掉 vue2
響應(yīng)式數(shù)據(jù)定義的約束,因?yàn)樽罱K還是用 Object.defineProperty
去做對象攔截,插件同樣也提供了 set API
讓你去操作對象新增屬性等操作。
總結(jié)
通過上面的了解,相信你一定對于 Vue2
如何使用 composition API
有了一定的了解,因?yàn)?API
相當(dāng)多, 響應(yīng)式相關(guān)的就還有 toRefs、toRef、unref、shallowRef、triggerRef
等等,這里就不一一分析,有興趣的可以繼續(xù)看源碼的實(shí)現(xiàn)。
寫 Vue2
的同學(xué)也可以不用羨慕寫 Vue3
的同學(xué)了,直接引入到項(xiàng)目就可以使用起來,雖然沒有 vue3
那么好的體驗(yàn),但是絕大部分場景還是相同的,使用時(shí)注意 README
文檔最后的限制章節(jié),里面講了一些使用限制。
(學(xué)習(xí)視頻分享:vuejs入門教程、編程基礎(chǔ)視頻)
The above is the detailed content of Analyze the principle of Vue2 implementing composition API. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

As a C# developer, our development work usually includes front-end and back-end development. As technology develops and the complexity of projects increases, the collaborative development of front-end and back-end has become more and more important and complex. This article will share some front-end and back-end collaborative development techniques to help C# developers complete development work more efficiently. After determining the interface specifications, collaborative development of the front-end and back-end is inseparable from the interaction of API interfaces. To ensure the smooth progress of front-end and back-end collaborative development, the most important thing is to define good interface specifications. Interface specification involves the name of the interface

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning

Combination of Golang and front-end technology: To explore how Golang plays a role in the front-end field, specific code examples are needed. With the rapid development of the Internet and mobile applications, front-end technology has become increasingly important. In this field, Golang, as a powerful back-end programming language, can also play an important role. This article will explore how Golang is combined with front-end technology and demonstrate its potential in the front-end field through specific code examples. The role of Golang in the front-end field is as an efficient, concise and easy-to-learn
