美文网首页
Composition API 使用

Composition API 使用

作者: 翔子丶 | 来源:发表于2021-04-16 18:14 被阅读0次

    响应性基础 API

    mkdir 03-composition-api
    # 初始化项目package.json
    npm init --yes
    # 安装vue3
    npm install vue@next --save
    
    • reactive返回对象的响应式副本

      <!-- 01-createApp.html  -->
      <!DOCTYPE html>
      <html lang="en">
        <head>
          <meta charset="UTF-8" />
          <meta http-equiv="X-UA-Compatible" content="IE=edge" />
          <meta name="viewport" content="width=device-width, initial-scale=1.0" />
          <title>createApp & reactive</title>
        </head>
        <body>
          <div id="app">
            x: {{ position.x }}<br />
            y: {{ position.y }}
          </div>
          <script type="module">
            import {
              createApp,
              reactive,
            } from './node_modules/vue/dist/vue.esm-browser.js'
      
            const app = createApp({
              setup() {
                // reactive用于设置对象响应式
                const position = reactive({
                  x: 0,
                  y: 0,
                })
                return {
                  position,
                }
              },
              mounted() {
                this.position.x = 100
              },
            })
            app.mount('#app')
          </script>
        </body>
      </html>
      

      可以将鼠标移动的相关的参数和方法统一封装在一个函数中,使用toRefs将响应式对象转换为普通对象

      // 将鼠标移动相关统一放在一起
      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)
        })
        // 返回时转换为ref
        return toRefs(position)
      }
      

      然后在 setup 函数中使用

      setup() {
        // 通过toRefs可以在不失去响应性的情况下解构
          const { x, y } = useMousePosition()
          return {
              x,
              y,
          }
      }
      
    • ref 接受一个内部值并返回一个响应式且可变的 ref 对象

      ...
      <div id="app">
        <button @click="increase">增加</button>
        <span>{{ count }}</span>
      </div>
      ...
      <script type="module">
        function useRef() {
          const count = ref(0)
      
          return {
            count,
            increase: () => {
              //
              count.value++
            },
          }
        }
        const app = createApp({
          setup() {
            return {
              ...useRef(),
            }
          },
        })
      </script>
      
    • computed 接受一个 getter 函数,并为从 getter 返回的值返回一个不变的响应式 ref 对象

      ...
      <div id="app">
        <button @click="push">按钮</button>
        未完成:{{ activeCount }}
      </div>
      ...
      <script type="module">
        const data = [
          { text: '看书', completed: false },
          { text: '敲代码', completed: false },
          { text: '约会', completed: true },
        ]
      
        createApp({
          setup() {
            const todos = reactive(data)
      
            const activeCount = computed(() => {
              return todos.filter((item) => !item.completed).length
            })
      
            return {
              activeCount,
              push: () => {
                todos.push({
                  text: '开会',
                  completed: false,
                })
              },
            }
          },
        }).mount('#app')
      </script>
      
    • watch watch 与 Options API this.$watch(以及相应的 watch 选项) 完全等效

      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')
      
    • watchEffect 在响应式地跟踪其依赖项时立即运行一个函数,并在更改依赖项时重新运行它

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

    项目地址

    相关文章

      网友评论

          本文标题:Composition API 使用

          本文链接:https://www.haomeiwen.com/subject/mvoelltx.html