当前位置:网站首页>New features of vue3

New features of vue3

2020-11-06 22:11:00 The front end of the attack

Crack vue3.x New characteristics

Video address

https://www.bilibili.com/video/av69262619/

0. Basic requirements

  1. Learn about common ES6 New characteristics

    • ES6 Import and export syntax of

    • Deconstruct assignment

    • Arrow function

    • etc…

  2. understand vue 2.x Basic use of

    • Components

    • Common instructions

    • Life cycle function

    • computed、watch、ref etc.

1. Related resources

  • 【 You know - Vue Function-based API RFC】https://zhuanlan.zhihu.com/p/68477600

  • 【github - vuejs/composition-api】https://github.com/vuejs/composition-api

  • 【github - composition-api/CHANGELOG.md】https://github.com/vuejs/composition-api/blob/master/CHANGELOG.md

  • 【 Open source in China - Yuxi announced Vue 3.0 Development route : Will rewrite... From scratch 3.0】https://www.oschina.net/news/100515/plans-for-the-next-iteration-of-vue-js

2. Initialize project

  1. install vue-cli3

    npm install -g @vue/cli
    # OR
    yarn global add @vue/cli
  2. Create project

    vue create my-project
    # OR
    vue ui
  3. Install... In the project composition-api Experience vue3 New characteristics

    npm install @vue/composition-api --save
    # OR
    yarn add @vue/composition-api
  4. In use of any @vue/composition-api Before the ability to provide , Must pass first Vue.use() Installation

    import Vue from 'vue'
    import VueCompositionApi from '@vue/composition-api'
    
    Vue.use(VueCompositionApi)

    After installing the plug-in , You can use the new Composition API To develop components .

3. setup

setup() The function is vue3 in , New properties for components . It's for us to use vue3 Of Composition API New features provide a unified entry point .

3.1 Execution opportunity

setup The function will be in the beforeCreate after 、created Before execution

3.2 receive props data

  1. stay props Defines the parameter names that the current component allows external passing :

    props: {
         
      p1: String
    }
  2. adopt setup Functional First parameter , receive props data :

    setup(props) {
         
        console.log(props.p1)
    }

3.3 context

setup The second parameter of a function is a Context object , This context object contains some useful properties , These attributes are in vue 2.x We need to go through this To access , stay vue 3.x in , They are accessed as follows :

const MyComponent = {
   
  setup(props, context) {
   
    context.attrs
    context.slots
    context.parent
    context.root
    context.emit
    context.refs
  }
}

Be careful : stay setup() Cannot access... In function this

4. reactive

reactive() Function to receive a normal object , Returns a responsive data object .

4.1 Basic grammar

Equivalent to vue 2.x Medium Vue.observable() function ,vue 3.x Provided in reactive() function , Used to create responsive data objects , The basic code example is as follows :

import {
    reactive } from '@vue/composition-api'

//  Create responsive data objects , Got  state  Be similar to  vue 2.x  in  data()  Response object returned 
const state = reactive({
    count: 0 })

4.2 Define responsive data for template Use

  1. Import on demand reactive function :

    import {
          reactive } from '@vue/composition-api'
  2. stay setup() Call in function reactive() function , Create responsive data objects :

    setup() {
         
         //  Create responsive data objects 
    	const state = reactive({
         count: 0})
    
         // setup  Function will respond to the data object  return  get out , for  template  Use 
    	return state
    }
  3. stay template Access to responsive data :

    <p> Current  count  The value is :{
        {count}}</p>

5. ref

5.1 Basic grammar

ref() Function to create a... Based on a given value Response type Of Data objects ,ref() The return value of a function call is an object , This object contains only one .value attribute :

import {
    ref } from '@vue/composition-api'

//  Create responsive data objects  count, The initial value is  0
const count = ref(0)

//  If you want to access  ref()  The value of the created responsive data object , Must pass  .value  Property is OK 
console.log(count.value) //  Output  0
//  Give Way  count  Value  +1
count.value++
//  Print again  count  Value 
console.log(count.value) //  Output  1

5.2 stay template Medium visit ref Create responsive data

  1. stay setup() Create responsive data in :

    import {
          ref } from '@vue/composition-api'
    
    setup() {
         
    	const count = ref(0)
    
         return {
         
             count,
             name: ref('zs')
         }
    }
  2. stay template Access to responsive data :

    <template>
      <p>{
        {count}} --- {
        {name}}</p>
    </template>

5.3 stay reactive Object ref Create responsive data

When put ref() Created responsive data objects , Mount to reactive() Upper time , Will automatically put the response data object Expand to original value , No need to pass .value Can be accessed directly , for example :

const count = ref(0)
const state = reactive({
   
  count
})

console.log(state.count) //  Output  0
state.count++ //  There is no need to pass  .value  You can access the original values directly 
console.log(count) //  Output  1

Be careful : new ref Will overwrite the old ref, The sample code is as follows :

//  establish  ref  And mount  reactive  in 
const c1 = ref(0)
const state = reactive({
   
  c1
})

//  Create again  ref, Name it  c2
const c2 = ref(9)
//  take   used  ref c1  Replace with   new  ref c2
state.c1 = c2
state.c1++

console.log(state.c1) //  Output  10
console.log(c2.value) //  Output  10
console.log(c1.value) //  Output  0

6. isRef

isRef() Used to determine whether a value is ref() Created objects ; Application scenarios : When you need to expand a certain possibility for ref() When creating the value , for example :

import {
    isRef } from '@vue/composition-api'

const unwrapped = isRef(foo) ? foo.value : foo

7. toRefs

toRefs() The function can change reactive() Created responsive objects , Convert to a normal object , It's just , Every attribute node on this object , All are ref() Type of responsive data , The most common application scenarios are as follows :

import {
    toRefs } from '@vue/composition-api'

setup() {
   
    //  Define responsive data objects 
	const state = reactive({
   
      count: 0
    })

    //  Define the event handlers available on the page 
    const increment = () => {
   
      state.count++
    }

    //  stay  setup  Returns an object for the page to use 
    //  This object can contain responsive data , You can also include event handlers 
    return {
   
      //  take  state  Every attribute on , All converted to  ref  Form of responsive data 
      ...toRefs(state),
      //  Self increasing event handler 
      increment
    }
}

The page can be accessed directly setup() in return Out of the responsive data :

<template>
  <div>
    <p> Current count The value is :{
  {count}}</p>
    <button @click="increment">+1</button>
  </div>
</template>

8. computed

computed() Used to create calculated properties ,computed() The return value of the function is a ref Example . Use computed Before you need to import... On demand :

import {
    computed } from '@vue/composition-api'

8.1 Create a read-only calculated property

Calling computed() During function , Pass in a function function , You can get a read-only calculated property , The sample code is as follows :

//  Create a  ref  Responsive data 
const count = ref(1)

//  according to  count  Value , Create a responsive calculated property  plusOne
//  It will depend on  ref  Automatically calculates and returns a new  ref
const plusOne = computed(() => count.value + 1)

console.log(plusOne.value) //  Output  2
plusOne.value++ // error

8.2 Create readable and writable calculation properties

Calling computed() During function , Pass in a containing get and set Object of function , You can get a readable and writable calculation property , The sample code is as follows :

//  Create a  ref  Responsive data 
const count = ref(1)

//  Create a  computed  Compute properties 
const plusOne = computed({
   
  //  Value function 
  get: () => count.value + 1,
  //  The mutator 
  set: val => {
   
    count.value = val - 1
  }
})

//  The operation of assigning values to calculated properties , Will trigger  set  function 
plusOne.value = 9
//  Trigger  set  After the function ,count  The value of will be updated 
console.log(count.value) //  Output  8

9. watch

watch() Function is used to monitor the change of some data items , This triggers certain actions , Need to import on demand before using :

import {
    watch } from '@vue/composition-api'

9.1 Basic usage

const count = ref(0)

//  Definition  watch, as long as  count  Value change , It will trigger  watch  Callback 
// watch  Will be automatically called once at creation time 
watch(() => console.log(count.value))
//  Output  0

setTimeout(() => {
   
  count.value++
  //  Output  1
}, 1000)

9.2 Monitor the specified data source

monitor reactive Data source of type :

//  Define data sources 
const state = reactive({
    count: 0 })
//  monitor  state.count  The change of this data node 
watch(
  () => state.count,
  (count, prevCount) => {
   
    /* ... */
  }
)

monitor ref Data source of type :

//  Define data sources 
const count = ref(0)
//  Specify the data source to monitor 
watch(count, (count, prevCount) => {
   
  /* ... */
})

9.3 Monitoring multiple data sources

monitor reactive Data source of type :

const state = reactive({
    count: 0, name: 'zs' })

watch(
  [() => state.count, () => state.name], // Object.values(toRefs(state)),
  ([count, name], [prevCount, prevName]) => {
   
    console.log(count) //  new  count  value 
    console.log(name) //  new  name  value 
    console.log('------------')
    console.log(prevCount) //  old  count  value 
    console.log(prevName) //  new  name  value 
  },
  {
   
    lazy: true //  stay  watch  When created , Do not execute the code in the callback function 
  }
)

setTimeout(() => {
   
  state.count++
  state.name = 'ls'
}, 1000)

monitor ref Data source of type :

const count = ref(0)
const name = ref('zs')

watch(
  [count, name], //  Many that need to be monitored  ref  data source 
  ([count, name], [prevCount, prevName]) => {
   
    console.log(count)
    console.log(name)
    console.log('-------------')
    console.log(prevCount)
    console.log(prevName)
  },
  {
   
    lazy: true
  }
)

setTimeout(() => {
   
  count.value++
  name.value = 'xiaomaolv'
}, 1000)

9.4 Clear surveillance

stay setup() Function watch monitor , It will automatically stop when the current component is destroyed . If you want to explicitly stop a surveillance , You can call watch() The return value of the function is just , The grammar is as follows :

//  Create a monitor , And get the   Stop function 
const stop = watch(() => {
   
  /* ... */
})

//  Call stop function , Clear the corresponding monitor 
stop()

9.5 stay watch Clear invalid asynchronous tasks

occasionally , When watch When the monitored value changes , or watch By itself stop after , We expect to be able to clean up those invalid asynchronous tasks , here ,watch A callback function is provided cleanup registrator function To carry out the cleanup . This cleanup function will be called in the following cases :

  • watch It's repeated
  • watch Forced stop

Template The code example in is as follows

/* template  The code in  */ <input type="text" v-model="keywords" />

Script The code example in is as follows

//  Define responsive data  keywords
const keywords = ref('')

//  Asynchronous task : Print keywords entered by users 
const asyncPrint = val => {
   
  //  Time delay  1  Print in seconds 
  return setTimeout(() => {
   
    console.log(val)
  }, 1000)
}

//  Definition  watch  monitor 
watch(
  keywords,
  (keywords, prevKeywords, onCleanup) => {
   
    //  Perform asynchronous tasks , And get to close the asynchronous task  timerId
    const timerId = asyncPrint(keywords)

    //  If  watch  Monitoring is repeated , The last outstanding asynchronous task will be cleared first 
    onCleanup(() => clearTimeout(timerId))
  },
  // watch  It is not executed when it is first created 
  {
    lazy: true }
)

//  hold  template  Data needed in  return  get out 
return {
   
  keywords
}

10. LifeCycle Hooks

New life cycle functions , It can be imported into components on demand , And only in setup() Use in a function , The code example is as follows :

import {
    onMounted, onUpdated, onUnmounted } from '@vue/composition-api'

const MyComponent = {
   
  setup() {
   
    onMounted(() => {
   
      console.log('mounted!')
    })
    onUpdated(() => {
   
      console.log('updated!')
    })
    onUnmounted(() => {
   
      console.log('unmounted!')
    })
  }
}

The following list , yes vue 2.x Life cycle function and new version Composition API Mapping between :

  • beforeCreate -> use setup()
  • created -> use setup()
  • beforeMount -> onBeforeMount
  • mounted -> onMounted
  • beforeUpdate -> onBeforeUpdate
  • updated -> onUpdated
  • beforeDestroy -> onBeforeUnmount
  • destroyed -> onUnmounted
  • errorCaptured -> onErrorCaptured

11. provide & inject

provide() and inject() Data transfer between nested components can be realized . These two functions can only be used in setup() Use in a function . Use... In parent components provide() Function to pass data down ; Use... In child components inject() Get the data from the upper layer .

11.1 Share common data

App.vue The root component :

<template>
  <div id="app">
    <h1>App  The root component </h1>
    <hr />
    <LevelOne />
  </div>
</template>

<script>
import LevelOne from './components/LevelOne'
// 1.  Import on demand  provide
import { provide } from '@vue/composition-api'

export default {
  name: 'app',
  setup() {
    // 2. App  The root component is the parent component , adopt  provide  Function to share data with child components ( No hierarchy )
    //    provide(' The name of the data to share ',  Shared data )
    provide('globalColor', 'red')
  },
  components: {
    LevelOne
  }
}
</script>

LevelOne.vue Components :

<template>
  <div>
    <!-- 4.  Bind by attributes , Set the font color for the label  -->
    <h3 :style="{color: themeColor}">Level One</h3>
    <hr />
    <LevelTwo />
  </div>
</template>

<script>
import LevelTwo from './LevelTwo'
// 1.  Import on demand  inject
import { inject } from '@vue/composition-api'

export default {
  setup() {
    // 2.  call  inject  Function time , By specifying the data name , Get the data shared by the parent 
    const themeColor = inject('globalColor')

    // 3.  Put the received shared data  return  to  Template  Use 
    return {
      themeColor
    }
  },
  components: {
    LevelTwo
  }
}
</script>

LevelTwo.vue Components :

<template>
  <div>
    <!-- 4.  Bind by attributes , Set the font color for the label  -->
    <h5 :style="{color: themeColor}">Level Two</h5>
  </div>
</template>

<script>
// 1.  Import on demand  inject
import { inject } from '@vue/composition-api'

export default {
  setup() {
    // 2.  call  inject  Function time , By specifying the data name , Get the data shared by the parent 
    const themeColor = inject('globalColor')

    // 3.  Put the received shared data  return  to  Template  Use 
    return {
      themeColor
    }
  }
}
</script>

11.2 share ref Responsive data

The following code realizes the function of switching theme colors by clicking buttons , Major modifications App.vue Code in component ,LevelOne.vue and LevelTwo.vue The code in is not subject to any changes :

<template>
  <div id="app">
    <h1>App  The root component </h1>

	<!--  Click on  App.vue  Button in , Toggle the color of the text in the subcomponent  -->
    <button @click="themeColor='red'"> Red </button>
    <button @click="themeColor='blue'"> Blue </button>
    <button @click="themeColor='orange'"> Orange </button>

    <hr />
    <LevelOne />
  </div>
</template>

<script>
import LevelOne from './components/LevelOne'
import { provide, ref } from '@vue/composition-api'

export default {
  name: 'app',
  setup() {
    //  Definition  ref  Responsive data 
    const themeColor = ref('red')

    //  hold  ref  Data is passed through  provide  The supplied subcomponent uses 
    provide('globalColor', themeColor)

    // setup  in  return  Data for current component  Template  Use 
    return {
      themeColor
    }
  },
  components: {
    LevelOne
  }
}
</script>

12. template refs

adopt ref() You can also reference elements or components on a page .

12.1 Reference to element

The sample code is as follows :

<template>
  <div>
    <h3 ref="h3Ref">TemplateRefOne</h3>
  </div>
</template>

<script>
import { ref, onMounted } from '@vue/composition-api'

export default {
  setup() {
    //  Create a  DOM  quote 
    const h3Ref = ref(null)

    //  stay  DOM  After the first load , To get a reference to an element 
    onMounted(() => {
      //  by  dom  Element set font color 
      // h3Ref.value  It's original DOM object 
      h3Ref.value.style.color = 'red'
    })

    //  Put the created reference  return  get out 
    return {
      h3Ref
    }
  }
}
</script>

12.2 References to components

TemplateRefOne.vue The sample code in is as follows :

<template>
  <div>
    <h3>TemplateRefOne</h3>

    <!-- 4.  Click the button to display the  count  value  -->
    <button @click="showNumber"> obtain TemplateRefTwo Medium count value </button>

    <hr />
    <!-- 3.  Add... To the component  ref  quote  -->
    <TemplateRefTwo ref="comRef" />
  </div>
</template>

<script>
import { ref } from '@vue/composition-api'
import TemplateRefTwo from './TemplateRefTwo'

export default {
  setup() {
    // 1.  Create a component of  ref  quote 
    const comRef = ref(null)

    // 5.  In the presentation subcomponent  count  Value 
    const showNumber = () => {
      console.log(comRef.value.count)
    }

    // 2.  Put the created reference  return  get out 
    return {
      comRef,
      showNumber
    }
  },
  components: {
    TemplateRefTwo
  }
}
</script>

TemplateRefTwo.vue Sample code in :

<template>
  <div>
    <h5>TemplateRefTwo --- {
  {count}}</h5>
    <!-- 3.  Click button , Give Way  count  Value on the  +1 -->
    <button @click="count+=1">+1</button>
  </div>
</template>

<script>
import { ref } from '@vue/composition-api'

export default {
  setup() {
    // 1.  Define responsive data 
    const count = ref(0)

    // 2.  Put responsive data  return  to  Template  Use 
    return {
      count
    }
  }
}
</script>

13. createComponent

This function is not necessary , Unless you want the perfect combination TypeScript Provide type inference for project development .

This function only provides type inference , Convenience is in combination with TypeScript When writing code , for setup() Medium props Provide complete type inference .

import {
    createComponent } from 'vue'

export default createComponent({
   
  props: {
   
    foo: String
  },
  setup(props) {
   
    props.foo // <- type: string
  }
})

版权声明
本文为[The front end of the attack]所创,转载请带上原文链接,感谢