Composition API will be Vue 3 Core functions of , It has many changes and performance improvements . We can also be in the Vue 2 Passed in npm plug-in unit
@vue/composition-api Use it . I will take you to understand :
*
@vue/composition-api common api use
*
vue3 Code logic extraction and reuse
*
How to use provide+inject replace vuex programme
vue2 use composition-api
Master file main.ts perhaps app.vue add to
import Vue from 'vue' import VueCompositionAPI from '@vue/composition-api'
Vue.use(VueCompositionAPI)
Composition API No more incoming data,mounted Isoparametric , Through the introduction of ref,onMounted
And so on , Execution of life cycle function .
Core grammar
reactive: Receives a normal object and returns a responsive proxy for that normal object .
ref: Accept a parameter value and return a responsive and changeable ref object .ref Object has a single property that points to an internal value .value.
computed: Pass in a getter function , Returns a default value that cannot be modified manually ref object .
readonly: Pass in an object ( Responsive or normal ) or ref, Returns a read-only proxy for the original object . A read-only proxy is “ Deep ”, Any nested properties within an object are also read-only .
watchEffect: Execute an incoming function immediately , And track their dependencies responsively , And rerun the function when its dependency changes . The return value can be explicitly called to stop listening .
watch: All equivalent to 2.x this.\$watch ( as well as watch Corresponding options in ).
setup function
Now the first one API namely setup function .setup Function is a new component option . As used within components Composition API
Entry point for . Let's take a look at the simple first demo
<template> <button @click="increase">count is: {{ count }}</button>
</template> <script> export default { setup() { let count = 0
const increase = () => count++ return { count, increase } },
} </script>
1, Call time
Create component instance , Then initialize props , And then it's called setup function . from vue2 From the perspective of life cycle hook , It will be there beforeCreate After the hook ,
created Previously called .
2, Used in template
If setup Returns an object , The properties of the object are merged into the rendering context of the component template .
3, Render function / JSX Used in
setup You can also return a function , Functions can also use the current setup Responsive data in function scope :
import { h, ref, reactive } from '@vue/composition-api' export default {
setup() { const count = ref(0)
const object = reactive({ foo: 'bar' })
return () => h('div', [count.value, object.foo]) }, }
4, Two parameters props( be careful props Object is responsive ),context( Context object , From the original 2.x in this Selective exposure of some property.)
const MyComponent = { setup(props, context) { let { attrs,
emit, isServer, listeners, parent, refs,
root, slots, ssrContext, } = context }, }
ref & reactive
stay App.vue in , Click event bound increase, And then it changed count, But the page didn't change , that is because setup In the object returned by the function count
Not responsive data , So how to create responsive data ? At this point, we need to master the responsive system API, We can use it ref and reactive establish .
<template> <button @click="increase"> count is: {
{ count }}, state.count is {{ state.count }} </button> </template> <script>
import { ref, reactive } from 'vue' export default { setup() {
let count = ref(0) // { value: 0 }
let state = reactive({ number: 0 }) const increase = () => {
count.value++ state.count++ }
return { count, state, increase } }, } </script>
Accept a parameter value and return a responsive and changeable ref object .ref Object has a single property that points to an internal value .value.
When ref Returns as a property of the rendering context ( That is, in setup() In the returned object ) And when used in templates , It will automatically unravel , No additional writing is required in the template .value
Vue It already has "ref" It's a new concept . But just to get it in the template DOM Element or component instance (“ Template reference ”). new ref The system is used for both logical state and template reference .
reactive Receives a normal object and returns a responsive proxy for that normal object .
Responsive conversion is “ Deep ”: Affects all nested properties within an object . be based on ES2015 Of Proxy
realization , The proxy object returned is not equal to the original object . It is recommended to use only proxy objects and avoid relying on original objects .
Do not deconstruct the returned proxy object , That would make it less responsive :
<template> <button @click="increase">count is: {{ count }}</button>
</template> <script> import { ref, reactive } from '@vue/composition-api'
export default { setup() { let state = reactive({ count: 0 })
const increase = () => state.count++
return { ...state, increase } // open state Property will lose responsiveness }, } </script>
toRef and toRefs
So if we really want to start state Properties of , Use in template count instead of state.count What should we do ? We can use it toRef and toRefs
these two items. API, Convert to ref object , I've talked about it before ref Objects can be used directly in templates .
toRef Can be used for a reactive Object to create a ref. this ref Can be delivered and can remain responsive .
<template> <button @click="increase"> count is: {{ count }},count2 is: {
{ count2 }} </button> </template> <script>
import { ref, reactive, toRef, toRefs } from '@vue/composition-api'
export default { setup() { let state = reactive({ count: 0 })
let countRef = toRef(state, 'count')
let state2 = reactive({ count2: 0 })
const increase = () => state.count++
let stateAsRefs = toRefs(state2)
return { count: countRef, increase, ...stateAsRefs } }, } </script>
Converting a responsive object into a normal object , Each of the property It's all one ref , And responsive objects property One to one correspondence .
computed & watch
const countDouble = computed(() => count.value * 2) watch(
() => state.count, (count, prevCount) => { /* ... */ } )
Code logic extraction and reuse
Composition API The first obvious advantage of is that it's easy to extract logic . It's solved
Logic extraction
export const useCount = (number) => { const count = ref(0)
const increase = () => { count.value += 1 } const reset = () => {
count.value = 0 } onMounted(() => { count.value = number })
return { count, increase, reset, } }
code reuse
// Another file uses : const { count, increase } = useCount(1) console.log(count) // output 1
increase() console.log(count) // output 2 reset() console.log(count) // output 0
Effectively solved the problem mixins Reuse naming conflict , It's hard to identify where the name comes from mixin Problems with documents .
replace vuex State management
state store It can be placed in a single file or directory , For example, setting a global component can only use the configuration config
//context/config.ts
import { provide, inject, ref, onMounted, readonly } from '@vue/composition-api'
const configSymbol: symbol = Symbol() export const useProvider = { setup() {
let config = ref(null) const configServer = async () => {
// await Some asynchronous operations , such as api etc. config.value = { name: ' name ' } }
onMounted(async () => { await configServer() })
provide(configSymbol, { // Export read only config Only the internal part of the function can modify the state
config: readonly(config), }) }, } export const useInject = () => {
return inject(configSymbol) }
Components at the top ( for example main.ts) Upper injection ,config It can be used in all components
import { defineComponent } from '@vue/composition-api'
import { useProvider } from './context/config' export default defineComponent({
setup() { useProvider() }, })
Business logic page usage config
import { useInject } from './context/config' const Components = { setup() {
const { config } = useInject() console.log(config.value.name) // output “ name ”
return { config, } }, }
Technology
Daily Recommendation