Big front-end study notes -- Composition API

Composition API

1. Use of Composition API

1. Using Vue3.0

First create an empty folder, then enter the folder to execute npm init -y, then execute npm install vue@3.0.0-rc.1 to install vue3.0

Create index.html, use of 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: the 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 () {
        // The first parameter props, the reactive object, cannot be destructed
        // The second parameter 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 in front of 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>

3. reactive-toRefs-ref

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

reactive is to convert ordinary objects into responsive objects, and ref is to wrap basic type data into responsive 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) // Convert primitive data into reactive objects
      return {
        count,
        increase: () => {
          count.value++
        }
      }
    }

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

4. Computed

computed can create a responsive data that depends on other responsive data, which is a computed property.

  • first usage

    • computed(() => count.value + 1)
  • 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>undone:{{activeCount}}</span>
  </div>
  <script type="module">
    import { createApp, reactive, computed } from './node_modules/vue/dist/vue.esm-browser.js'
    const data = [
      { text: 'reading', complated: false },
      { text: 'typing code', complated: false },
      { text: 'Dating', complated: true },
    ]

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

Five, watch

1. 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 that is executed after monitoring the data change. This function has two parameters which are the new value and the old value.
  • The third parameter: options object, deep and immediate

2. The return value of watch

  • function to cancel listening

use:

<body>
  <div id="app">
    Please choose one yes/no The problem:
    <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>

6. WatchEffect

  • is a simplified version of the watch function, also used to monitor data changes
  • Accepts a function as a parameter and listens for changes in reactive data within 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>

Tags: Front-end Vue

Posted by gukii on Mon, 16 May 2022 15:18:02 +0300