关于uniapp + ts 的一些总结,uniapp组件通信

完整的对比一下

首先,先来回忆一下uniapp的基础写法

<script>
export default{
    data(){
        return {}
    },
    methods:{},
    computed:{},
    filters:{},
    watch:{},
    onLoad:{}
}
</script>

下面是 uniapp + ts 的一些写法

<template>
	<view class="content">
		<view>
			<text class="title">{{title}}</text>
		</view>
		<view>
			<text class="title">{{age}}</text>
			<button @click="addHandler(1)">+1</button>
		</view>
		<Child :question="question" @answer="answerHandler"></Child>
		<view>{{answer ? answer : ''}}</view>
		<AnotherChild></AnotherChild>
	</view>
</template>

<script lang="ts">
	import { Vue, Component, Watch } from 'vue-property-decorator'
	import Child from './components/Child'
	import AnotherChild from './components/AnotherChild'

	@Component({
		components: {
			Child,
			AnotherChild
		}
	})
	export default class Index extends Vue{
		// data
		private title:String = 'Hello World'; 
		private num:Number = 123; 
		private question:String = '怎么才能光吃不胖呢'; 
		private answer:String = '';
		//计算属性
		get age():Number{ 
			return this.num;
		}
		// 生命周期
		private onLoad(){
			this.printTitle();
		}
		// watch监听器
		@Watch('num') //watch,此处是监听title的变化
		onNumChange(newVal:Number,oldVal:Number){
			console.log(newVal,oldVal);
		}
		// 方法
		private printTitle():void{ //methods
			console.log('hahahhhaha')
		}
		private addHandler(n: any):void {
			this.num = this.num + n
		}
		private answerHandler(val: String) {
			this.answer = val
		}
	}
</script>

uniapp组件通信

1. 父传子

// 父组件
<Child :question="question"></Child>

// 子组件
// prop属性
@Prop(String) private question!: string;
<text class="title">{{question}}</text>

2. 子传父

// 子组件
<button @click="emitHandler">子组件向父组件触发自定义事件</button>
// Emit子组件触发
@Emit('answer')
private emitHandler() {
  return "无解"
}

// 父组件
<Child @answer="answerHandler"></Child>
private answerHandler(val: String) {
	this.answer = val
}

3. 兄弟组件之间通信

// 子组件A
<button @click="brotherHandler">兄弟组件传值</button>
// 方法
private brotherHandler() {
  uni.$emit('addMoney', 100)
}

// 子组件B
private created() {
  uni.$on('addMoney',num => {
    this.money += num
  })
}

如果有不对的地方,欢迎指正哦~

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值