VUE3.x展望

37521 ワード

ドキュメント:
API Reference
チュートリアル
レッスン
1.プロジェクトの初期化
// ① npm i -g @vue/cli
// ② vue create my-project
// ③ npm install @vue/composition-api -S

// ④ main,js
import Vue from 'vue'
import VueCompositionApi from '@vue/composition-api'
Vue.use(VueCompositionApi)

2.setupメソッドsetupvue3.xの新しいコンポーネント属性を操作する方法であり、コンポーネント内部にすべての属性と方法が露出する統一APIである.
2.1実行タイミング
setupの実行タイミング:beforeCreateの後にcreatedする前に
setup(props, ctx) {
      console.log('setup')
  },
  beforeCreate() {
    console.log('beforeCreate')
  },
  created() {
    console.log('created')
  },

2.2 propsデータを受け入れる


 
//    setup         ,   props   :
setup(props) {
  console.log(props)
},
//   props                     :
props: {
    p1: String
}
/*
{}
p1: "    com-setup"
get p1: ƒ reactiveGetter()
set p1: ƒ reactiveSetter(newVal)
__proto__: Object
*/

 
2.3 context setup関数の2番目のパラメータは、vue 2.xにアクセスするためにthisに必要ないくつかの有用な属性を含むコンテキストオブジェクトです.
  setup(props, ctx) {
    console.log(ctx)
    console.log(this) // undefined
  },
/*
attrs: Object
emit: ƒ ()
listeners: Object
parent: VueComponent
refs: Object
root: Vue
...
*/

注意:vue 3.x関数ではsetup()にアクセスできません.
3. reactive this関数は、一般的な関数を受信し、応答式のデータオブジェクトを返します.reactive関数はreactivevue 2.x関数と等価であり、Vue.observable()にはvue 3.x関数が提供され、応答式のデータオブジェクトを作成するために使用され、基本コードの例は以下の通りである.


<span style="color: #000000;">
import {reactive} from </span>'@vue/composition-api'<span style="color: #000000;">
export </span><span style="color: #0000ff;">default</span><span style="color: #000000;"> {
  setup(props, ctx) {
    </span><span style="color: #008000;">//</span><span style="color: #008000;">          ,    state     vue 2.x   data()         </span>
    const state = reactive({ count: 0<span style="color: #000000;"> })
    state.count </span>+= 1<span style="color: #000000;">
    console.log(state)
     </span><span style="color: #008000;">//</span><span style="color: #008000;"> setup             return   ,  template   </span>
    <span style="color: #0000ff;">return</span><span style="color: #000000;"> state
  }
}
</span>

4. ref reactive()関数は、指定された値に基づいて応答型のデータ・オブジェクトを作成するために使用されます.ref()関数呼び出しの戻り値は、1つのref()属性のみを含むオブジェクトです.


<span style="color: #000000;">
import { ref } from </span>'@vue/composition-api'<span style="color: #000000;">
export </span><span style="color: #0000ff;">default</span><span style="color: #000000;"> {
  setup() {
    </span><span style="color: #008000;">//</span><span style="color: #008000;"> /           count,     0</span>
    const refCount = ref(0<span style="color: #000000;">)
    </span><span style="color: #008000;">//</span><span style="color: #008000;">       ref()               ,     .value      ,   setup      .value   </span>
    console.log(refCount.value) <span style="color: #008000;">//</span><span style="color: #008000;">    0</span>
    <span style="color: #008000;">//</span><span style="color: #008000;">   refCount    +1</span>
        refCount.value++
    <span style="color: #008000;">//</span><span style="color: #008000;">      refCount   </span>
        console.log(refCount.value) <span style="color: #008000;">//</span><span style="color: #008000;">    1</span>
    <span style="color: #0000ff;">return</span><span style="color: #000000;"> {
      refCount
    }
  }
}
</span>

4.1 reactiveオブジェクトでrefにアクセスして作成されたレスポンスデータ.valueで作成された応答型データオブジェクトをref()にマウントすると、応答型データオブジェクトは自動的に元の値に展開され、reactive()で直接アクセスする必要はありません.たとえば、次のようになります.
setup() {
  const refCount = ref(0)
  const state = reactive({refCount})
  console.log(state.refCount) //    0
  state.refCount++ //         .value          
  console.log(refCount) //    1
  return {
    refCount
  }
}

注意:新しいrefは古いrefを上書きします.サンプルコードは次のとおりです.
setup() {
  //    ref      reactive  
  const c1 = ref(0);
  const state = reactive({ c1 });

  //      ref,    c2
  const c2 = ref(9);
  //     ref c1       ref c2
  state.c1 = c2;
  state.c1++;

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

5. isRef .valueある値がisRef()で作成されたオブジェクトであるかどうかを判断するために使用される.適用シーン:ref()で作成可能な値を展開する必要がある場合、たとえば:
import { ref, reactive, isRef } from "@vue/composition-api";
export default {
  setup() {
    const unwrapped = isRef(foo) ? foo.value : foo
  }
};

6. toRefs ref()関数はtoRefs()で作成された応答式オブジェクトを通常のオブジェクトに変換することができるが、このオブジェクト上の各属性ノードは、reactive()タイプの応答式データである.


<span style="color: #000000;">
import { reactive, toRefs } from </span>"@vue/composition-api"<span style="color: #000000;">;
export </span><span style="color: #0000ff;">default</span><span style="color: #000000;"> {
  setup() {
    </span><span style="color: #008000;">//</span><span style="color: #008000;">      </span>
    const state = reactive({ count: 0, name: "zs"<span style="color: #000000;"> });
    </span><span style="color: #008000;">//</span><span style="color: #008000;">   </span>
    const add = () =><span style="color: #000000;"> {
      state.count </span>+= 1<span style="color: #000000;">;
    };
    </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> {
      </span><span style="color: #008000;">//</span><span style="color: #008000;">       </span>
      <span style="color: #008000;">//</span><span style="color: #008000;"> ...state,</span>
      <span style="color: #008000;">//</span><span style="color: #008000;">      </span>
<span style="color: #000000;">      ...toRefs(state),
      add
    };
  }
};
</span>

 
7.computed計算属性
7.1読み取り専用の計算プロパティ


<span style="color: #000000;">
import { computed, ref } from </span>'@vue/composition-api'<span style="color: #000000;">
export </span><span style="color: #0000ff;">default</span><span style="color: #000000;"> {
  setup() {
    const refCount </span>= ref(1<span style="color: #000000;">)
    </span><span style="color: #008000;">//</span><span style="color: #008000;">   </span>
    let computedCount = computed(() => refCount.value + 1<span style="color: #000000;">)
    console.log(computedCount)
    </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> {
      refCount,
      computedCount
    }
  }
};
</span>

7.2読み書き可能な計算属性


<span style="color: #000000;">
import { computed, ref } from </span>'@vue/composition-api'<span style="color: #000000;">
export </span><span style="color: #0000ff;">default</span><span style="color: #000000;"> {
  setup() {
    const refCount </span>= ref(1<span style="color: #000000;">)
    </span><span style="color: #008000;">//</span><span style="color: #008000;">     </span>
    let computedCount =<span style="color: #000000;"> computed({
      </span><span style="color: #008000;">//</span><span style="color: #008000;">     </span>
      get: () => refCount.value + 1<span style="color: #000000;">,
      </span><span style="color: #008000;">//</span><span style="color: #008000;">     </span>
      set: val =><span style="color: #000000;"> {
        refCount.value </span>= refCount.value -5<span style="color: #000000;">
      }
    })
    console.log(computedCount.value)
    </span><span style="color: #008000;">//</span><span style="color: #008000;">           ,    set   </span>
    computedCount.value = 10<span style="color: #000000;">
    console.log(computedCount.value)
    </span><span style="color: #008000;">//</span><span style="color: #008000;">    set    ,count       </span>
<span style="color: #000000;">    console.log(refCount.value)
    </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> {
      refCount,
      computedCount
    }
  }
};
</span>

8. watch ref()関数は、特定のデータ・アイテムの変更を監視し、特定のアクションをトリガーするために使用されます.使用前に必要に応じてインポートする必要があります.
import { watch } from '@vue/composition-api'

8.1基本的な使い方


<span style="color: #000000;">
import { watch, ref } from </span>'@vue/composition-api'<span style="color: #000000;">
export </span><span style="color: #0000ff;">default</span><span style="color: #000000;"> {
  setup() {
    const refCount </span>= ref(100<span style="color: #000000;">)
    </span><span style="color: #008000;">//</span><span style="color: #008000;">    watch,   count    ,     watch   </span>
    <span style="color: #008000;">//</span><span style="color: #008000;">                 watch</span>
    watch(() => console.log(refCount.value), { lazy: <span style="color: #0000ff;">false</span><span style="color: #000000;">})
    setInterval(() </span>=><span style="color: #000000;"> {
      refCount.value </span>+= 2<span style="color: #000000;">
    }, </span>5000<span style="color: #000000;">)
    </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> {
      refCount
    }
  }
};
</span>

8.2データソースの監視
監視watch()タイプのデータソース:


<span style="color: #000000;">
import { watch, ref, reactive } from </span>'@vue/composition-api'<span style="color: #000000;">
export </span><span style="color: #0000ff;">default</span><span style="color: #000000;"> {
  setup() {
    const state </span>= reactive({count: 100<span style="color: #000000;">})
    watch(
      </span><span style="color: #008000;">//</span><span style="color: #008000;">   count</span>
      () =><span style="color: #000000;"> state.count,
      </span><span style="color: #008000;">//</span><span style="color: #008000;">            </span>
      (newVal, oldVala) =><span style="color: #000000;"> {
        console.log(newVal, oldVala)
      },
      { lazy: </span><span style="color: #0000ff;">true</span><span style="color: #000000;"> }
    )
    setInterval(() </span>=><span style="color: #000000;"> {
      state.count </span>+= 2<span style="color: #000000;">
    }, </span>5000<span style="color: #000000;">)
    </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> state
  }
};
</span>

監視reactiveタイプのデータソース:
export default {
  setup() {
    //      
    let count = ref(0);
    //          
    watch(count, (count, prevCount) => {
      console.log(count, prevCount)
    })
    setInterval(() => {
      count.value += 2
    }, 2000)
    console.log(count.value)
    return {
      count
    }
  }
};

8.3複数のデータソースの傍受
監視refタイプのデータソース:
export default {
  setup() {
    const state = reactive({count: 100, name: 'houfei'})
    watch(
      //   count name
      [() => state.count, () => state.name],
      //            
      ([newCount, newName], [oldCount, oldName]) => {
        console.log(newCount, oldCount)
        console.log(newName, oldName)
      },
      { lazy: true} //   watch       ,           
    )
    setTimeout(() => {
      state.count += 2
      state.name = 'qweqweewq'
    }, 3000)
    return state
  }
};

監視reactiveタイプのデータソース:
export default {
  setup() {
    //      
    const count = ref(10)
    const name = ref('zs')
    //          
    watch(
      [count, name],
      ([newCount, newName], [oldCount, oldName]) => {
        console.log(newCount, oldCount)
        console.log(newName, oldName)
      },
      { lazy: true}
    )
    setInterval(() => {
      count.value += 2
    }, 2000)
    console.log(count.value)
    return {
      count
    }
  }
};

8.4パージ監視ref関数内で作成されたsetup()モニタは、現在のコンポーネントが破棄されたときに自動的に停止します.監視を明確に停止するには、watch関数の戻り値を呼び出すとよい.

<span style="color: #008000;">//</span><span style="color: #008000;">     ,        </span>
const stop = watch(() =><span style="color: #000000;"> {
  </span><span style="color: #008000;">/*</span><span style="color: #008000;"> ... </span><span style="color: #008000;">*/</span><span style="color: #000000;">
})

</span><span style="color: #008000;">//</span><span style="color: #008000;">       ,       </span>
stop()</pre> 
 </div> 
 <p> </p> 
 <div class="cnblogs_code"> 
  <pre><template>
  <div>
    <!-- <h3>05.watch.vue  </h3> -->
    <p>count: {{ count }}</p>
    <button @click="stopWatch">    </button>
  </div>
</template>

<script><span style="color: #000000;">
import { watch, ref, reactive } from </span>"@vue/composition-api"<span style="color: #000000;">;
export </span><span style="color: #0000ff;">default</span><span style="color: #000000;"> {
  setup() {
    </span><span style="color: #008000;">//</span><span style="color: #008000;">      </span>
    const count = ref(10<span style="color: #000000;">)
    const name </span>= ref('zs'<span style="color: #000000;">)
    </span><span style="color: #008000;">//</span><span style="color: #008000;">          </span>
    const stop =<span style="color: #000000;"> watch(
      [count, name],
      ([newCount, newName], [oldCount, oldName]) </span>=><span style="color: #000000;"> {
        console.log(newCount, oldCount)
        console.log(newName, oldName)
      },
      { lazy: </span><span style="color: #0000ff;">true</span><span style="color: #000000;">}
    )
    setInterval(() </span>=><span style="color: #000000;"> {
      count.value </span>+= 2<span style="color: #000000;">
      name.value </span>= 'houyue'<span style="color: #000000;">
    }, </span>2000<span style="color: #000000;">)
    </span><span style="color: #008000;">//</span><span style="color: #008000;">     </span>
    const stopWatch = () =><span style="color: #000000;"> {
      console.log(</span>"    ,        "<span style="color: #000000;">)
      stop()
    }
    console.log(count.value)
    </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> {
      stop,
      count,
      stopWatch
    }
  }
};

</span>

 
8.5 watchで無効な非同期タスクをクリアする
場合によっては、watch()によって監視された値が変化した場合、またはwatch自体がwatchによってその後、無効な非同期タスクをクリアすることが望ましい場合があります.この場合、stopコールバック関数には、watchがクリアの動作を実行するために提供されます.このパージ関数は、次のように呼び出されます.
watchは繰り返し実行されたwatch強制cleanup registrator function了Templateのコードの例は次のとおりです.


Scriptのコードの例は次のとおりです.
<span style="color: #000000;">
import { watch, ref, reactive } from </span>"@vue/composition-api"<span style="color: #000000;">;

export </span><span style="color: #0000ff;">default</span><span style="color: #000000;"> {
  setup() {
    </span><span style="color: #008000;">//</span><span style="color: #008000;">         keywords</span>
    const keywords = ref(""<span style="color: #000000;">);

    </span><span style="color: #008000;">//</span><span style="color: #008000;">     :          </span>
    const asyncPrint = val =><span style="color: #000000;"> {
      </span><span style="color: #008000;">//</span><span style="color: #008000;">    1     </span>
      <span style="color: #0000ff;">return</span> setTimeout(() =><span style="color: #000000;"> {
        console.log(val);
      }, </span>1000<span style="color: #000000;">);
    };

    </span><span style="color: #008000;">//</span><span style="color: #008000;">    watch   </span>
<span style="color: #000000;">    watch(
      keywords,
      (keywords, prevKeywords, onCleanup) </span>=><span style="color: #000000;"> {
        </span><span style="color: #008000;">//</span><span style="color: #008000;">       ,           timerId</span>
        const timerId =<span style="color: #000000;"> asyncPrint(keywords);
        </span><span style="color: #008000;">//</span><span style="color: #008000;">    watch         ,               </span>
        onCleanup(() =><span style="color: #000000;"> clearTimeout(timerId));
      },
      </span><span style="color: #008000;">//</span><span style="color: #008000;"> watch           </span>
      { lazy: <span style="color: #0000ff;">true</span><span style="color: #000000;"> }
    );

    </span><span style="color: #008000;">//</span><span style="color: #008000;">   template        return   </span>
    <span style="color: #0000ff;">return</span><span style="color: #000000;"> {
      keywords
    };
  }
};
</span>

9.provide&injectコンポーネント評価stopおよびprovide()は、ネストされたコンポーネント間のデータ伝達を実現することができる.この2つの関数は、inject()関数でのみ使用できます.親コンポーネントでsetup()関数を使用してデータを下に転送します.サブレベルコンポーネントでは、provide()を使用して上位レベルから渡されたデータを取得します.
9.1共通データの共有inject()ルートコンポーネント:


<span style="color: #000000;">
import { ref, provide } from </span>'@vue/composition-api'<span style="color: #000000;">
import Son from </span>'./components/06.son.vue'<span style="color: #000000;">

export </span><span style="color: #0000ff;">default</span><span style="color: #000000;"> {
  name: </span>'app'<span style="color: #000000;">,
  components: {
    </span>'son'<span style="color: #000000;">: Son
  },
  setup() {
    const color </span>= ref('green'<span style="color: #000000;">)
    provide(</span>'themecolor'<span style="color: #000000;">, color)
    </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> {
      color
    }
  }
}
</span>
app.vuesonコンポーネント:


<span style="color: #000000;">
import { inject } from </span>'@vue/composition-api'<span style="color: #000000;">
import Grandson from </span>'./07.grandson.vue'<span style="color: #000000;">
export </span><span style="color: #0000ff;">default</span><span style="color: #000000;"> {
    components: {
    </span>'grandson'<span style="color: #000000;">: Grandson
  },
  setup() {
    const color </span>= inject('themecolor'<span style="color: #000000;">)
    </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> {
      color
    }
  }
}
</span>
06.son.vuesonコンポーネント:


<span style="color: #000000;">
import { inject } from </span>'@vue/composition-api'<span style="color: #000000;">
export </span><span style="color: #0000ff;">default</span><span style="color: #000000;"> {
  setup() {
    const color </span>= inject('themecolor'<span style="color: #000000;">)
    </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> {
      color
    }
  }
}
</span>

9.2共有07.grandson.vue応答データrefルートコンポーネント:


<span style="color: #000000;">
import { provide } from </span>'@vue/composition-api'<span style="color: #000000;">
import Son from </span>'./components/06.son.vue'<span style="color: #000000;">

export </span><span style="color: #0000ff;">default</span><span style="color: #000000;"> {
  name: </span>'app'<span style="color: #000000;">,
  components: {
    </span>'son'<span style="color: #000000;">: Son
  },
  setup() {
    provide(</span>'themecolor', 'red'<span style="color: #000000;">)
  }
}
</span>
app.vuesonコンポーネント:


<span style="color: #000000;">
import { inject } from </span>'@vue/composition-api'<span style="color: #000000;">
import Grandson from </span>'./07.grandson.vue'<span style="color: #000000;">
export </span><span style="color: #0000ff;">default</span><span style="color: #000000;"> {
    components: {
    </span>'grandson'<span style="color: #000000;">: Grandson
  },
  setup() {
    const color </span>= inject('themecolor'<span style="color: #000000;">)
    </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> {
      color
    }
  }
}
</span>
06.son.vuesonコンポーネント:


<span style="color: #000000;">
import { inject } from </span>'@vue/composition-api'<span style="color: #000000;">
export </span><span style="color: #0000ff;">default</span><span style="color: #000000;"> {
  setup() {
    const color </span>= inject('themecolor'<span style="color: #000000;">)
    </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> {
      color
    }
  }
}
</span>

10.ノードの参照template ref
10.1 domの参照


<span style="color: #000000;">
import { ref, onMounted } from </span>'@vue/composition-api'<span style="color: #000000;">

export </span><span style="color: #0000ff;">default</span><span style="color: #000000;"> {
  setup() {
    </span><span style="color: #008000;">//</span><span style="color: #008000;">      DOM   </span>
    const h3Ref = ref(<span style="color: #0000ff;">null</span><span style="color: #000000;">)

    </span><span style="color: #008000;">//</span><span style="color: #008000;">   DOM         ,          </span>
    onMounted(() =><span style="color: #000000;"> {
      </span><span style="color: #008000;">//</span><span style="color: #008000;">   dom         </span>
      <span style="color: #008000;">//</span><span style="color: #008000;"> h3Ref.value    DOM  </span>
      h3Ref.value.style.color = 'red'<span style="color: #000000;">
    })

    </span><span style="color: #008000;">//</span><span style="color: #008000;">        return   </span>
    <span style="color: #0000ff;">return</span><span style="color: #000000;"> {
      h3Ref
    }
  }
}
</span>

10.2コンポーネントの参照07.grandson.vue親コンポーネント:


<span style="color: #000000;">

import Son from </span>'./components/06.son.vue'<span style="color: #000000;">

export </span><span style="color: #0000ff;">default</span><span style="color: #000000;"> {
  name: </span>'app'<span style="color: #000000;">,
  components: {
    </span>'son'<span style="color: #000000;">: Son
  },
  setup() {
    const comRef </span>= ref(<span style="color: #0000ff;">null</span><span style="color: #000000;">) 
    const showComRef </span>= () =><span style="color: #000000;"> {
      console.log(comRef)
      console.log(</span>'str1   ' +<span style="color: #000000;"> comRef.value.str1)
      comRef.value.setStr1()
    }
    </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> {
      comRef,
      showComRef
    }
  }
}
</span>
Appサブアセンブリ:


<span style="color: #000000;">
import { ref } from </span>'@vue/composition-api'<span style="color: #000000;">
export </span><span style="color: #0000ff;">default</span><span style="color: #000000;"> {
  setup() {
    const str1 </span>= ref('       !!'<span style="color: #000000;">)
    const setStr1 </span>= () =><span style="color: #000000;"> {
      str1.value </span>= '    '<span style="color: #000000;">
    }
    </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> {
      str1,
      setStr1
    }
  }
}
</span>

11 nextTick
<template>
  <div>
    <h3>09.nextTick   h3>
    <p>   $nextTickp>
    <button v-if="isShowInput === false" @click="showInput">     button>
    <input type="text" v-else ref="ipt">
  div>
template>

<script>
export default {
  data() {
    return {
      isShowInput: false
    }
  },
  methods: {
    showInput() {
      this.isShowInput = !this.isShowInput
      // console.log(this.$refs)
      this.$nextTick(() => {
        this.$refs.ipt.focus()
      })
    }
  }
}
script>