前端與移動開發之vue-day4(1)
阿新 • • 發佈:2018-11-19
父元件向子元件傳值
元件例項定義方式,注意:一定要使用props屬性來定義父元件傳遞過來的資料
<script> // 建立 Vue 例項,得到 ViewModel var vm = new Vue({ el: '#app', data: { msg: '這是父元件中的訊息' }, components: { son: { template: '<h1>這是子元件 --- {{finfo}}</h1>', props: ['finfo'] } } }); </script> 使用v-bind或簡化指令,將資料傳遞到子元件中: <div id="app"> <son :finfo="msg"></son> </div>
子元件向父元件傳值
原理:父元件將方法的引用,傳遞到子元件內部,子元件在內部呼叫父元件傳遞過來的方法,同時把要傳送給父元件的資料,在呼叫方法的時候當作引數傳遞進去;
父元件將方法的引用傳遞給子元件,其中,getMsg是父元件中methods中定義的方法名稱,func是子元件呼叫傳遞過來方法時候的方法名稱
<son @func="getMsg"></son> 子元件內部通過this.$emit('方法名', 要傳遞的資料)方式,來呼叫父元件中的方法,同時把資料傳遞給父元件使用 <div id="app"> <!-- 引用父元件 --> <son @func="getMsg"></son> <!-- 元件模板定義 --> <script type="x-template" id="son"> <div> <input type="button" value="向父元件傳值" @click="sendMsg" /> </div> </script> </div> <script> // 子元件的定義方式 Vue.component('son', { template: '#son', // 元件模板Id methods: { sendMsg() { // 按鈕的點選事件 this.$emit('func', 'OK'); // 呼叫父元件傳遞過來的方法,同時把資料傳遞出去 } } }); // 建立 Vue 例項,得到 ViewModel var vm = new Vue({ el: '#app', data: {}, methods: { getMsg(val){ // 子元件中,通過 this.$emit() 實際呼叫的方法,在此進行定義 alert(val); } } }); </script> 元件中data和props的區別評論列表案例 目標:主要練習父子元件之間傳值 使用 this.$refs 來獲取元素和元件 <div id="app"> <div> <input type="button" value="獲取元素內容" @click="getElement" /> <!-- 使用 ref 獲取元素 --> <h1 ref="myh1">這是一個大大的H1</h1> <hr> <!-- 使用 ref 獲取子元件 --> <my-com ref="mycom"></my-com> </div> </div> <script> Vue.component('my-com', { template: '<h5>這是一個子元件</h5>', data() { return { name: '子元件' } } }); // 建立 Vue 例項,得到 ViewModel var vm = new Vue({ el: '#app', data: {}, methods: { getElement() { // 通過 this.$refs 來獲取元素 console.log(this.$refs.myh1.innerText); // 通過 this.$refs 來獲取元件 console.log(this.$refs.mycom.name); } } }); </script>