1、先創建一個測試組件:
創建component目錄,新建test.vue文件,定義一個組件:
這個組件中,我們實現以下功能:
①父vue文件中傳遞屬性參數,改變msg的值
②父vue文件中調用子組件的函數
③子組件中調用父vue文件中的函數
<template> <view class="test"> {{msg}} <button type="default" @click="userFather()">調用父組件方法</button> </view> </template> <script> export default {
//父vue頁面傳遞給組件的參數獲取方式 props: { can1: { type: String, default: function() { return "null" } } },
//實時監聽某個變量變化 watch: { can1: { handler() { console.log(this.can1,"5556666"); this.msg = this.can1 }, //監聽到數據變化時立即執行 immediate: true }, }, data() { return { msg: "" } }, onLoad() { }, onShow() { }, methods: { userFather() { //第一種調用父組件函數的方法 this.$parent.sghdws('這是子組件參數'); //第二種調用父組件函數的方法 //this.$emit('sghdws', "這是子組件參數") }, open() { console.log("調用子組件方法"); } } } </script> <style> </style>
2、創建父vue文件
<template> <view> <!--通過can1進行傳參,同樣可以can2等,通過ref定義子組件的名稱,便於從vue文件中調用子組件中的函數--> <test1 :can1="suiji" ref="test1"></test1> <button type="default" @click="userChild()">調用子組件方法</button> </view> </template> <script> //引入組件 import test1 from "@/component/test.vue"; export default { //使用組件 components:{ test1 }, data() { return { suiji:'' } }, onLoad() { }, onShow() { var p_this = this; //當前時間,使得組件中的msg一直變化為當前時間(實現第一個需求) setInterval(function() { let h = new Date().getHours(); let i = new Date().getMinutes(); let s = new Date().getSeconds(); let hh = (h < 10) ? "0" + h : h; let ii = (i < 10) ? "0" + i : i; let ss = (s < 10) ? "0" + s : s; p_this.suiji = hh + ":" + ii + ":" + ss; }, 1000); }, methods: { //子組件調用父vue文件中的這個函數(實現第二個需求) sghdws(a) { console.log(a); }, //父vue文件調用這個函數,這個函數調用子組件中的函數(實現第三個需求) userChild() { console.log("父組件方法---------"); this.$refs.test1.open() } } } </script> <style> </style>
最終實現效果:

時間是從父vue文件中獲取出來的,通過屬性傳遞給了子組件,子組件中定義了變量監聽,實時更新時間,實現了父vue文件參數傳遞到子組件的需求
點擊“調用父組件方法”,可以調用父vue頁面的函數
點擊“調用子組件方法”,可以調用子組件頁面函數
