完整的对比一下

首先,先来回忆一下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
  })
}

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

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐