Composition API介紹

Composition API

Composition API介紹

Composition API字面意思是組合API,它是為了實現(xiàn)基于函數(shù)的邏輯復用機制而產(chǎn)生的。

調試環(huán)境搭建

方案一:

  • 遷出Vue3源碼: git clone https://github.com/vuejs/vue-next.git
  • 安裝依賴: yarn
  • 生成sourcemap文件,package.json

"dev": "node scripts/dev.js --sourcemap"

  • 編譯: yarn dev

生成結果:packages\vue\dist\vue.global.js

方案二:
在head標簽中引入以下

<script src="https://cdn.jsdelivr.net/npm/vue@3.0.0-beta.14/dist/vue.global.js"></script>

基本使用

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>hello vue3</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@3.0.0-beta.14/dist/vue.global.js"></script>
    <!-- <script src="../dist/vue.global.js"></script> -->
</head>

<body>
    hello vue3
    <div id='app'>
        <h2>{{state.count}}--{{count2}}---{{state.doubleCount}}</h2>
        <div @click="add">count: {{ state.count }}</div>
        <div @click="add2">count: {{ count2 }}</div>
    </div>
    <script>
        const { createApp, reactive, ref, computed, watch } = Vue
        // reactive: 接收一個普通對象然后返回該普通對象的響應式代理。等同于 2.x 的 Vue.observable()
        // ref: 接受一個參數(shù)值并返回一個響應式且可改變的 ref 對象。ref 對象擁有一個指向內部值的單一屬性 .value。
        // computed: 傳入一個 getter 函數(shù),返回一個默認不可手動修改的 ref 對象。
        // watch API 完全等效于 2.x this.$watch (以及 watch 中相應的選項)。watch 需要偵聽特定的數(shù)據(jù)源,并在回調函數(shù)中執(zhí)行副作用。默認情況是懶執(zhí)行的,也就是說僅在偵聽的源變更時才執(zhí)行回調。
        const App = {
            // setup 函數(shù)是一個新的組件選項。作為在組件內使用 Composition API 的入口點。
            // 調用時刻是初始化屬性props確定后,beforeCreate之前
            setup() {
                const count2 = ref(1)
                // 響應化:接收一個對象,返回一個響應式的代理對象
                const state = reactive({
                    count: 1,
                    // computed()返回一個不可變的響應式引用對象 
                    // 它封裝了getter的返回值 
                    doubleCount: computed(() => state.count * 2)
                })
                watch(
                    () => state.count,
                    (count, prevCount) => {
                        /* ... */
                        console.log('state.count', count, prevCount);

                    }
                )
                watch(count2, (count, prevCount) => {
                    /* ... */
                    console.log('count2', count, prevCount);
                })
                function add() {
                    state.count++
                }
                function add2() {
                    count2.value++
                }
                // 返回對象將和渲染函數(shù)上下文合并
                return { count2, state, add, add2 }
            }
        }
        createApp(App).mount('#app')
    </script>
</body>

</html>

簡單demo

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>hello vue3</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@3.0.0-beta.14/dist/vue.global.js"></script>
    <!-- <script src="../dist/vue.global.js"></script> -->
</head>

<body>
    hello vue3
    <div id='app'></div>
    <script>
        const { createApp, reactive, onMounted, onUnmounted, toRefs } = Vue;
        // 鼠標位置偵聽
        function useMouse() {

            const state = reactive({ x: 0, y: 0 })
            const update = e => {
                state.x = e.pageX
                state.y = e.pageY
            }
            onMounted(() => {
                window.addEventListener('mousemove', update)
            })
            onUnmounted(() => {
                window.removeEventListener('mousemove', update)
            })
            // 轉換所有key為響應式數(shù)據(jù)
            return toRefs(state)
        }
        // 事件監(jiān)測
        function useTime() {
            const state = reactive({ time: new Date() })
            onMounted(() => {
                setInterval(() => {
                    state.time = new Date()
                }, 1000)
            })
            return toRefs(state)
        }
        // 邏輯組合
        const MyComp = {
            template: `
                <div>x: {{ x }} y: {{ y }}</div>
                <p>time: {{time}}</p>
                `,
            setup() {
                // 使用鼠標邏輯
                const { x, y } = useMouse()
                // 使用時間邏輯
                const { time } = useTime()
                // 返回使用
                return { x, y, time }
            }
        }
        createApp(MyComp).mount('#app')


    </script>
</body>

</html>

參考鏈接:

官方文檔:
composition api

其他文檔:

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容