1. vue 中組件與組件之間通信的方式?
父 -> 子 prop
子 -> 父 子通過 $emit 觸發一個自定義事件 。 父在調用這個子組件的時候,監聽這個自定義事件即可
下面這兩種能實現,但是很繁瑣。我們有更好的方式叫做中央事件處理器或者vuex
兄 -> 弟 要通過父親來操作
表兄 -> 表弟 要通過爺爺
還有一些非常非常特殊的使用方式,一般不推薦使用:
1. $root 能夠獲取到根組件的實例對象
2. $parent 獲取父組件的實例對象
3. $children 獲取子組件們的實例對象集合 []
4. $refs 獲取具體某個子組件的實例或者具體某個html元素的真實dom。(這個東西在獲取具體某個html元素的時候常用。。。)
4.1 首先需要標記。你想要獲取的組件或者html元素,在他們身上定義一個 ref="xxx"
4.2 然后 this.$refs.xxx
如果 ref 標記的是普通html元素,那么到通過 $refs.xxx 得到的將是 這個 html元素的dom對象
如果 ref 標記的是一個子組件。那么 通過 $refs.xxx 得到的將是這個 子組件的 實例對象
//代碼視例
<script> Vue.component("parent", { data() { return { name: "張小三" }; }, template: ` <div class="parent"> <h1 ref="box2">我是 parent , 我的名字是 {{ name }}</h1> </div> `, created() { console.log(this.$children); } }); let vm = new Vue({ el: "#app", data: { name: "張三豐" }, template: ` <div id="app" class="root"> <button @click="fn1">獲取h1的真實dom對象</button> <h1 ref="box">我是老祖宗,根組件,我的名字是 {{ name }}</h1> <parent ref="box2" ></parent> </div> `, methods: { fn1() { // 該如何獲取 當前這個組件的 h1 的dom對象 1. console.log(document.getElementById("box")); // 不推薦使用,有副作用 2. console.log(this.$el.querySelector("#box")); // 可以使用,不會有副作用 // 3. 最推薦的方式 console.log(this.$refs["box"]); console.log(this.$refs.box2); // ? 需要獲取到 parent 組件中 h1 標簽的那個dom對象 console.log(this.$refs["box2"].$el.querySelector("h1")); console.log(this.$refs["box2"].$refs["box2"]); } } }); </script>