组件文件夹必须为components才会出现新建组件的选项
组件的使用和注册
test组件
<template>
<view>
这是test组件
这是父组件传递过来的数据{{title}}
<button @click="sendnum">给父组件传值</button>
</view>
</template>
<script>
export default {
props:['title'],
name:"test",
data() {
return {
num:3
};
},
beforeCreate() {
console.log("实例初始化之后调用")
},
created() {
console.log("实例创建完成后调用")
},
methods:{
sendnum(){
this.$emit('myEven',this.num)
}
}
}
</script>
<style>
</style>
在index页面导入组件 写在script中
<script>
import test from "../../components/test.vue"
</script>
注册组件
<script>
components:{
// key val一样直接省略写法 组件名:组件 test:test
test
}
</script>
使用组件
v-if的boolean值决定组件是否显示
<template>
<view class="content">
<test v-if="flag" :title="title" @myEven="getNum"></test>
<button @click="checktest">切换test组件</button>
</view>
</template>
子组件给父组件传值
预先定义好了num
子组件
<template>
<view>
这是test组件
这是父组件传递过来的数据{{title}}
<button @click="sendnum">给父组件传值</button>
</view>
</template>
子组件注册myEven事件
methods:{
sendnum(){
this.$emit('myEven',this.num)
}
}
父组件
父组件加载myEven事件
<template>
<view class="content">
<test v-if="flag" @myEven="getNum"></test>
<button @click="checktest">切换test组件</button>
子组件传递过来的数据:{{num}}
</view>
</template>
methods: {
getNum(num){
console.log(num)
this.num=num
}
},
父组件给子组件传值
父组件
在组件标签绑定title参数
<template>
<view class="content">
<test v-if="flag" :title="title" @myEven="getNum"></test>
<button @click="checktest">切换test组件</button>
子组件传递过来的数据:{{num}}
</view>
</template>
data() {
return {
title: 'Hello',
flag:true,
num:0
}
},
子组件
通过props接收参数
<script>
export default {
props:['title'],
name:"test",
}
</script>
<template>
<view>
这是test组件
这是父组件传递过来的数据{{title}}
<button @click="sendnum">给父组件传值</button>
</view>
</template>
兄弟组件之间传值
b组件使用uni.$on()注册全局事件
<template>
<view>
{{num}}
</view>
</template>
<script>
export default {
name:"b",
data() {
return {
num:0
};
},
created() {
// 注册全局事件
uni.$on("updateNum",(num)=>{
this.num+=num
})
}
}
</script>
<style>
</style>
a组件使用uni.$emit()触发全局事件
<template>
<view>
这是a组件<button @click="addNum">修改B组件的数据</button>
</view>
</template>
<script>
export default {
name:"a",
data() {
return {
};
},
methods:{
addNum(){
uni.$emit('updateNum',10)
}
},
}
</script>
<style>
</style>