Big front-end study notes - Composition API

Composition API

Article content output source: big front-end high-paying training camp

1. Use of Composition API

1. Use Vue3.0

First create an empty folder, then enter the folder to execute npm init -y, and then execute to npm install [email protected]install vue3.0

Create index.html, use vue3.0

<body>
  <div id="app">
    x: {
   
   { position.x }} <br>
    y: {
   
   { position.y }} <br>
  </div>
  <script type="module">
    import {
     
      createApp } from './node_modules/vue/dist/vue.esm-browser.js'

    const app = createApp({
     
     
      data () {
     
     
        return {
     
     
          position: {
     
     
            x: 0,
            y: 0
          }
        }
      }
    })
    console.log(app)

    app.mount('#app')
  </script>
</body>

2. Use of setup and reactive

  • createAPP: Create a Vue object
  • setup: Entry of CompositionAPI
  • reactive: create reactive objects
<body>
  <div id="app">
    x: {
   
   { position.x }} <br>
    y: {
   
   { position.y }} <br>
  </div>
  <script type="module">
    import {
     
      createApp, reactive } from './node_modules/vue/dist/vue.esm-browser.js'

    const app = createApp({
     
     
      setup () {
     
     
        // 第一个参数 props,响应式对象,不能被解构
        // 第二个参数 context, attrs、emit、slots
        const position = reactive({
     
     
          x: 0,
          y: 0
        })
        return {
     
     
          position
        }
      },
      mounted () {
     
     
        this.position.x = 2
      }
    })
    console.log(app)

    app.mount('#app')
  </script>
</body>

Second, the life cycle hook function in setup

Just capitalize the first letter of the vue hook function, and add on before the hook function. Special: destroy in the original life cycle corresponds to onUnmounted.

<body>
  <div id="app">
    x: {
   
   { position.x }} <br>
    y: {
   
   { position.y }} <br>
  </div>
  <script type="module">
    import {
     
      createApp, reactive, onMounted, onUnmounted } from './node_modules/vue/dist/vue.esm-browser.js'

    function useMousePosition () {
     
     
        const position = reactive({
     
     
          x: 0,
          y: 0
        })

        const update = e => {
     
     
          position.x = e.pageX
          position.y = e.pageY
        }

        onMounted(() => {
     
     
          window.addEventListener('mousemove', update)
        })

        onUnmounted(() => {
     
     
          window.removeEventListener('mousemove', update)
        })

        return position
    }

    const app = createApp({
     
     
      setup () {
     
     
        const position = useMousePosition()
        return {
     
     
          position
        }
      },
      mounted () {
     
     
        this.position.x = 2
      }
    })
    console.log(app)

    app.mount('#app')
  </script>
</body>

三、reactive-toRefs-ref

The reactive data created by reactive is no longer reactive after deconstruction. toRefs can also convert all the properties of the reactive object into reactive, so the object returned by toRefs can be deconstructed, and the data is still reactive after deconstruction.

Reactive is to convert ordinary objects into reactive objects, while ref is to package basic types of data into reactive objects.

Use of ref:

<body>
  <div id="app">
    <button @click="increase">Button</button>
    <span>{
   
   {count}}</span>
  </div>
  <script type="module">
    import {
     
      createApp, ref } from './node_modules/vue/dist/vue.esm-browser.js'

    function useCount () {
     
     
      const count = ref(0) // 将基本类型数据转化成响应式对象
      return {
     
     
        count,
        increase: () => {
     
     
          count.value++
        }
      }
    }

    createApp({
     
     
      setup () {
     
     
        return {
     
     
          ...useCount()
        }
      }
    }).mount('#app')
  </script>
</body>

Four, Computed

Computed can create a responsive data, this responsive data depends on other responsive data, which is a calculated attribute.

  • The first usage

    • computed(() => count.value + 1)
  • The second usage

    const count = ref(1)
    const plusOne = computed({
          
          
      get: () => count.value + 1,
      set: val => {
          
          
        count.value = val - 1
      }
    })
    

use:

<body>
  <div id="app">
    <button @click="push">Button</button>
    <span>未完成:{
   
   {activeCount}}</span>
  </div>
  <script type="module">
    import {
     
      createApp, reactive, computed } from './node_modules/vue/dist/vue.esm-browser.js'
    const data = [
      {
     
      text: '看书', complated: false },
      {
     
      text: '敲代码', complated: false },
      {
     
      text: '约会', complated: true },
    ]

    createApp({
     
     
      setup () {
     
     
        const todos = reactive(data)
        const activeCount = computed(() => {
     
     
          return todos.filter(item => !item.complated).length
        })
        return {
     
     
          activeCount,
          push: () => {
     
     
            todos.push({
     
     
              text: '开会',
              complated: false
            })
          }
        }
      }
    }).mount('#app')
  </script>
</body>

Five, watch

1. The three parameters of watch

  • The first parameter: the data to be monitored must be the object returned by reactive or ref
  • The second parameter: the function to be executed after monitoring the data change, this function has two parameters, the new value and the old value
  • The third parameter: option object, deep and immediate

2. The return value of watch

  • Function to cancel listening

use:

<body>
  <div id="app">
    请选择一个yes/no的问题:
    <input v-model.lazy="question">
    <p>{
   
   {answer}}</p>
  </div>
  <script type="module">
    import {
     
      createApp, ref, watch } from './node_modules/vue/dist/vue.esm-browser.js'

    createApp({
     
     
      setup () {
     
     
        const question = ref('')
        const answer = ref('')
        watch(question, async (newValue, oldValue) => {
     
     
          const response = await fetch('https://www.yesno.wtf/api')
          const data = await response.json()
          answer.value = data.answer
        })
        return {
     
     
          question,
          answer
        }
      }
    }).mount('#app')
  </script>
</body>

六、WatchEffect

  • Is a simplified version of the watch function, also used to monitor changes in data
  • Accept a function as a parameter, monitor the changes of the responsive data in the function
<body>
  <div id="app">
    <button @click="increase">increase</button>
    <button @click="stop">stop</button>
    <p>{
   
   {count}}</p>
  </div>
  <script type="module">
    import {
     
      createApp, ref, watchEffect } from './node_modules/vue/dist/vue.esm-browser.js'

    createApp({
     
     
      setup () {
     
     
        const count = ref(0)
        const stop = watchEffect(() => {
     
     
          console.log(count.value)
        })
        return {
     
     
          count,
          stop,
          increase: () => count.value ++
        }
      }
    }).mount('#app')
  </script>
</body>

Guess you like

Origin blog.csdn.net/jal517486222/article/details/108689508