uniapp自定义组件
一、自定义组件使用方式:
1.编写组件img-border.vue
<template>
<image class="img" :src="src" @click="onClickImg"></image>
</template>
<script>
export default{
props:{
src:String
},
methods:{
onClickImg(){
this.$emit('onClick',this.src)
},
}
}
</script>
<style>
image.img{
display: block;
}
</style>
2.注册并使用组件
<template>
<view class="content">
<!-- 使用组件 -->
<img-border src="../../static/image/logo.png" @onClick="onClickImg"></img-border>
</view>
</template>
<script>
import imgBorder from "@/components/img-border"; //引入组件
export default {
components: { //注册组件
imgBorder
},
methods: {
onClickImg(e) {
//点击子组件
console.log(e)
},
},
}
</script>
注意:组件名称和组件值相同可以省略只写一个(原来格式:imgBorder:imgBorder)
二、组件间传值
引入组件的叫父组件,被引入的叫子组件
(1)父向子传值,通过属性的方式
父组件向子组件img-border通过属性名src传递一个字符串,子组件通过props进行接收数据
<!-- 父组件 -->
<img-border src="../../static/image/logo.png"></img-border>
<!-- 子组件 -->
<template>
<image class="img" :src="src" ></image>
</template>
<script>
export default{
props:{
src:String
},
}
</script>
(2)子向父传值,通过触发事件的方式
子组件通过$emit()触发事件的方式向父组件传递数据,父组件通过监听事件的方式来接收数据
<!-- 子组件 --> <image class="img" :src="src" @click="onClickImg"></image> export default{ methods:{ onClickImg(){ this.$emit('onClick',this.src) }, } } <!-- 父组件 --> <img-border src="../../static/image/logo.png" @onClick="onClickImg"></img-border> onClickImg(e) { //点击子组件 console.log(e) },

浙公网安备 33010602011771号