函式式元件:透過函式呼叫的方式新增元件。
傳統呼叫元件方式的困擾:
<Child v-if='isShow' :msg='msg'/> <botton @click='btnClick' /> import Child from '@/components/Child' let isShow = ref(false); let msg = ref('111'); let btnClick = ()=>{ isShow.value = true; msg.value = 222;
...
isShow.value = false; }
1,這種非馬上就要渲染的元件,需要大量程式碼去控制他,比如需要申明是否新增元件的變數,傳遞的屬性變數==
2,其他地方也要這麼寫,讓人頭皮發麻
函式式呼叫元件:
let btnClick = ()=>{
createChildComponent("222");
}
//呼叫函式,就會自動新增元件,引數透過函式傳遞。
//呼叫方便,簡單粗暴。
函式式元件的實現:toast舉例
<!--Toast.vue 元件檔案的建立是一樣的--> <template> <div class="page"> <div class="toast">{{msg}}</div> </div> </template> <script setup> import { ref,defineProps } from 'vue'; let {msg} = defineProps({ msg:{ default:"請求成功!" } }); </script> <style lang='scss' scoped> .page{ position: fixed; width: 100vw; height: 100vh; .toast{ background-color: rgba(0,0,0,0.6); margin-bottom: 10px; border-radius: 5px; width: 160px; height: 30px; display: flex; align-items: center; justify-content: center; font-size: 20px; color:#eeeeee; } } </style>
<!--Toast.js 裡面匯出建立上面toast元件的函式--> import { createApp } from "vue"; import Toast from "@/components/Toast.vue"; //dom要掛載到的dom export default function createToastComponent(msg) { //createApp建立元件例項 let instance = createApp(Toast,{msg}); let mountNode = document.createElement('div'); document.body.appendChild(div); //將元件掛載相應的dom上 instance.mount(mountNode); setTimeout(()=>{ //解除安裝元件 instance.unmount(); //解除安裝元件後,把渲染的html一併清除 document.body.removeChild(mountNode); },1000); } <!--Parent.vue呼叫--> import createToastComponent from '@components/Toast.js' let btnClick()=>{ createToastComponent('222'); }
說明:
1,CreateApp(component,prop)返回一個元件例項,第一個引數是個元件,第二個引數是要傳遞的屬性
比如檔案main.js 就有下面兩句
import App from './App.vue'
let app = createApp(App);
2,mount 將元件例項掛載到一個dom上,引數是一個dom元素(比如createElement,或queryElement的元素)或類選擇器,
mount掛載到dom上,會導致dom裡面的所有內容全部清空。這就是上面的例子中為什麼新建一個dom來掛載mount的原因。
mount掛載dom必須已經渲染出來,main.js 中的app.mount('#app');
生成的index.html入口是下面這樣的,透過defer載入js檔案,保證下面的<div id='app'></div>先渲染出來
<!DOCTYPE html> <html lang=""> <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"> <link rel="icon" href="/favicon.ico"> <title>screen</title> <script defer src="/js/chunk-vendors.js"></script><script defer src="/js/app.js"></script></head> <body> <noscript> <strong>We're sorry but screen doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"></div> <!-- built files will be auto injected --> </body> </html>
3,unmount解除安裝元件函式