前言:最近公司安排做一個仿微信聊天的小程序,先實現聊天的基本功能,在項目過程中遇到一些小的知識點,在這里做下筆記;
由於之前沒有用過VUE,也沒有做過小程序,在看了VUE官網和uniapp官網后,開始邊學邊做。
一,子組件調用父組件的方法
子組件 IMMsg
<template> <view> <button @tap="showData(items)">獲取數據</button> </view> </template> <script> export default { name: 'IMMsg', props:{ }, data() { return { items:[ { 'key':'content', 'label':'內容' } ] }; }, methods:{ showData: function(data) { this.$emit("msg", data); } } } </script> <style> </style>
父組件中調用子組件的showData方法
父組件 chat.vue
<template> <view> <IMsg @msg="showData"></IMsg> </view> </template> <script> // 引入 IM 組件 import IMsg from '../../components/IMsg.vue'; export default { data() { return { datas:'' }; }, methods: { showData: function(dd) { this.datas=dd; console.log(this.datas); } }, components:{ IMsg } }; </script> <style></style>
輸出結果:
二,父組件調用子組件的方法
子組件 IMMsg
<template> <view> </view> </template> <script> export default { name: 'IMMsg', props:{ }, data() { return { items:[ { 'key':'content', 'label':'內容' } ] }; }, methods:{ showData: function(data) { console.log(this.items); } } } </script> <style> </style>
父組件 chat.vue
<template> <view> <IMsg ref="IMsg"></IMsg> <button @tap="getData">調用子組件的方法</button> </view> </template> <script> // 引入 IM 組件 import IMsg from '../../components/IMsg.vue'; export default { data() { return { datas:'' }; }, methods: { getData: function() { this.$refs.IMsg.showData(); } }, components:{ IMsg } }; </script> <style></style>
注:父組件可以通過$refs拿到子組件的對象
然后直接調用子組件的 methods里的方法和data里的數據
打印結果: