父組件:
<!-- .default: 綁定小程序冒泡型事件,如bindtap,.default後綴可省略不寫;
.stop: 綁定小程序捕獲型事件,如catchtap;
.user: 綁定用戶自定義組件事件,通過$emit觸發。注意,如果用了自定義事件,則events中對應的監聽函數不會再執行。 -->
<template>
<Test @childFn.user="parentFn" :title="parentTitle1" :syncTitle.sync="parentTitle" :twoWayTitle.sync="parentNum" /> <view>{{reversedMessage}}</view>
</template>
import Test from './test';
watch = { parentNum (newValue, oldValue){ console.log(newValue,oldValue) } }; data = { parentTitle: '666', parentTitle1:'123', parentNum:1, }; computed = { // 計算屬性reversedMessage,在腳本中可通過this.reversedMessage來引用,在模板中可通過{{ reversedMessage }}來插值 //只要是組件中有任何數據發生了改變,那麼所有計算屬性就都會被重新計算。 reversedMessage() { return '長沙市教育局'.split('').reverse().join('') } }; methods = { //$invoke是一個頁面或組件對另一個組件中的方法的直接調用,通過傳入組件路徑找到相應的組件,然後再調用其方法。 //this.$invoke('ComA', 'someMethod', 'someArgs'); //this.$invoke('./../ComB/ComG', 'someMethod', 'someArgs');//someMethod方法名 someArgs參數 //父組件中的方法 parentFn(num){ this.parentNum += 1; this.$apply(); console.log(this.parentNum) this.$invoke('Test','testConsole','666')//調用Test組件中的testConsole方法,並傳遞參數666 }, }
//子組件 <template> <view bindtap="toClick"> {{title}}{{syncTitle}}{{twoWayTitle}} </view> </template> <script> import wepy from 'wepy' export default class Test extends wepy.component { data = { }; props = { // 靜態傳值 父子組件數據完全獨立互不干擾 title: String, // 父向子單向動態傳值 ,父組件傳值用.sync修飾符來達到父組件數據綁定至子組件的效果 syncTitle: { type: String, default: 'null' }, // twoWay: true來達到子組件數據綁定至父組件的效果 //如父組件傳值用到了.sync修飾符,子組件中同時設置了twoWay:true,則可以達到雙向綁定 twoWayTitle: { type: Number, default: 'nothing', twoWay: true } }; methods = { toClick(){ //(this.$parent.parentTitle)調用父組件傳過來的數據 this.$emit('childFn', 100) }, //測試通過$invoke調用其他組件中的方法 testConsole(arg){ console.log(arg) } } onLoad() { //console.log(this.title); //console.log(this.syncTitle); //console.log(this.twoWayTitle); } }; </script>