實現跨層元件通訊(Vue3___defineComponent)
阿新 • • 發佈:2021-10-25
常用的父子元件通訊方法:
//父元件 <template> <my-header:title="title"@changeTitle="changeTitle"></my-header> </tempale> <script> importmyHeaderfrom"@/components/Header.vue"; //引入元件 export default { data(){ return{ title:"父傳子測試" } }, components:{ "my-header":myHeader }, methods:{ changeTitle(val){this.title = val } } } </script> //子元件 myheader.vue <template> <h1>{{ title }}</h1> <button @click="triggerMethod">觸發父元件方法</button> </tempalte> <script> export default{ props:{//接收父元件出來的title title:{ type: String,default: "" } }, methods:{ triggerMethod:function(){ this.$emit("changeTitle","傳引數"); //子元件通過$emit與父元件通訊 } } } </script>
provide/inject(提供/注入),可以實現跨層元件(祖孫)間通訊,不需要將資料一層一層向下傳遞:
//父元件 Father.vue <template> <son></son> </template> <script> import { defineComponent, reactive, provide, computed } from"vue"; import son from "@/components/Son"; export default defineComponent({ components: { son }, setup() { let params = reactive({ name: "來自父親的引數" }) provide("name", computed(()=> params.name)); //用計算屬性返回值能夠動態傳遞來子/孫元件(當子孫元件通過方法觸發修改name值時) function changeName(val){ params.name = val; //子孫元件觸發 } provide("changeName",changeName); } }) </script>
//兒子元件 Son.vue <template> <h2>{{ name }}</h2> <button @click="changeName('兒子元件觸發')">兒子元件觸發Name修改</button> <div class="grandson"> <grandson></grandson> </div> </template> <script> import grandson from "@/components/grandson"; import { defineComponent, inject } from "vue"; export default defineComponent({ components: { grandson }, setup() { let name = inject("name"); //接收Father元件傳來的name let changeName = inject("changeName"); //接收方法 return { name, changeName, }; }, }); </script>
//孫子元件 grandson.vue <template> <h2>{{ name }}</h2> <button @click="changeName('孫子元件觸發')">孫子元件觸發Name修改</button> </template> <script> import { defineComponent, inject, watch } from "vue"; export default defineComponent({ name: "HelloWorld", setup() { let name = inject("name"); let changeName = inject("changeName"); watch(name,(newValue,oldValue)=>{ //這裡可以監聽name的變化 }) return { name, changeName, }; }, }); </script>
子孫元件都接收到Father元件傳來的引數"來自Father元件的引數"。
當點選兒子元件或者孫子元件按鈕時,觸發changeName事件在Father元件上修改name值。