父传子:
父组件:
<template>
<view :title=”title”>
</view>
</template>`在这里插入代码片`
<script>
export default {
name: 'app',
data () {
return {
title: ‘我是父组件’
}
}
}
</script>
子组件:通过props来接收
<template>
<view>
这是父组件传递过来的数据{title}
</view>
</template>
<script>
export default {
name: 'app',
data () {
return {
}
},
props:[‘title’],
}
</script>
子传父:(通过触发$emit)
子组件:
<
template>
<view>
<button @click=”send()”>给父组件传值</button>
</view>
</template>
<script>
export default {
name: 'app',
data () {
return {
num: 66
}
},
methods:{
send(){
console.log(‘给父组件传值了’)
this.$emit(‘myEmit’,this.num)//第一个参数是自定义事件,第二个参数是你想传递的值
}
}
}
</script>
父组件:子组件中定义了自定义事件,父组件就要在需要使用的地方使用它
<template>
<view @myEmit=”getNum”>
这是子组件传递过来的值{{num}}
</view>
</template>
<script>
export default {
name: 'app',
data () {
return {
num: 0 // 也可以把子组件传递过来的值存储起来,默认是0 ,传值过后值发生改变
}
},
methods:{
// 通过形参接收子组件传递过来的值
getNun(num){
console.log(num)
this.num = num
}
}
}
</script>
兄弟组件传值:
兄弟a组件
<template>
<view>
<button @click=”addNum()”>我要修改兄弟b组件中的数据</button>
</view>
</template>
<script>
export default {
name: 'app',
data () {
return {
}
},
methods:{
// 通过全局$emit 去触发b组件中的回调函数updateNum,同时还可以传递参数
addNum(){
uni.$emit(‘updateNum’, 10)
}
}
}
</script>
兄弟b组件:
<template>
<view>
这是b中的数据{{num}}
</view>
</template>
<script>
export default {
name: 'app',
data () {
return {
num:66
}
},
Created(){
uni.$on(‘updateNum’,num = >{
this.num + = num
})
}
methods:{
}
}
</script>
uni app 原生请求方式的封装
const BASE_URL = 'http:localhost:8080'
export const myRequest = (options)=>{
return new Promise((resolve,reject)=>{
uni.requset({
url: BASE_URL + options.url,
method:options.method || 'GET',
data: options.data || {},
success:(res)=>{
if(res.status !== 200) {
return uni.showToast({
title:'获取数据失败'
})
}
resolve(res)
},
fail:(err)=>{
uni.showToast({
title:'请求接口失败'
})
reject(err)
}
})
})
}