定義:
1.setup是處於beforecreate和created生命周期間的函數;
2.setup是組合式api的入口;
3.setup函數中定義的變量和方法都是需要return出去的,不然沒有辦法在模板中使用;
注意事項;
1.因為在setup中尚未執行created初始化完成,所以無法使用data,methods(vue2);
2.因為在setup中無法使用data,methods,所以為了避免錯誤使用,vue將setup函數中的this轉化成undefined;
3.setup是同步的,不能異步使用;
其他:
setup接收兩個參數(props,context(包括attrs,slots,emit)),
1.props:
是一個對象,接收父組件傳來的所有數據,你需要使用props:{}接收數據,如果你不配置props:{},那么會得到undefined;
<template> <div class="box"> 父組件 </div> <no-cont :mytitle="msg" othertitle="別人的標題" @sonclick="sonclick"> </no-cont> </template> <script lang="ts"> import NoCont from "../components/NoCont.vue" export default { setup () { let msg={ title:'父組件給子給子組件的數據' } function sonclick(msss:string){ console.log(msss) } return {msg,sonclick} }, components:{ NoCont } } </script>
<template> <div @click="sonHander"> 我是子組件中的數據 </div> </template> <script lang="ts"> import { defineComponent,setup } from 'vue'; export default defineComponent({ name: 'NoCont', // 未進行接受 // props:{ // mytitle:{ // type:Object // } // }, setup(props,context){ console.log('props==>',props.mytitle);//輸出的值是 undefined function sonHander(){ context.emit('sonclick','子組件傳遞給父組件') } return {sonHander} } }); </script>
2.context:
該屬性是獲取props{}中沒有被聲明接收的所有對象;