文章目录[隐藏]
  • 前言
  • 组件定义
  • 组件使用
  • 我定义的测试组件
  • 我定义的组件使用
  • 组件注意事项
  • 我的疑问

前言

在我使用uniapp中,免不了要去自定义一个组件,于是根据官方文档尝试定义了一个组件。

组件定义

新建一个 vue 文件,根据以下格式定义组件
<template name="组件名称">
    <view>
        ......
    </view>
</template>
<script>
export default {
    name: "组件名称",
    //属性
    props: {
        属性名称: {
            type: String,//属性类型
            value: "值"
        },
        ......
    },
    //组件生命周期
    created:function(e){
    
    },
    methods: {
        函数名称:function(obj){
        
        },
    }
}
</script>
<style>
组件样式
</style>

组件使用

1、引用组件
import 组件名称 from "../../components/组件名.vue";
2、注册组件
export default{
    components:{
        组件名称
    },
}
3、在试图模板中使用组件
<组件名称 组件属性="对应的值"></组件名称>

我定义的测试组件

新建一个 vue 文件,命名为 test-page.vue
<template name="testPage">
    <view @click="onClick('eee')">
        <text :text="text" :class="{backgroundColor}">{{text}}</text>  
        <!-- <view v-for="item in date" :key="index" :dataText="{text}">2</view> -->
    </view>
</template>

<script>
    
    export default {
        name: 'testPage',
        props: {
            text: {
                type: String,
                default: ''
            },
            test: {
                type: String,
                default: ''
            },
            date: {
                type: Array,
                default () {
                    return []
                }
            },
            backgroundColor: {
                type: String,
                default: '#fffbe8'
            }
        },
        data() {
            return {
                dataText: 'ddddd'
            }
        },
        methods: {
            onClick(e) {
                console.log(e);
                this.$emit('clickedA', e + "ddd")
            }
        }
    }
</script>

<style>

</style>

我定义的组件使用

<test-page :date="date" :text="noticeText" :test="mode" 
                        :backgroundColor="noticeText"
                        @clickedA="onClick"></test-page>

组件注意事项

组件直接参数传递方式和 vue 方法一样:
父组件 ---> 子组件传递通过 props; 
子组件---->父组件传值通过$emit 事件传递

我的疑问

父组件向子组件传递参数后,我想在子组件的属性中绑定 text 值,一直绑定不起。

但是用特殊的关键字又可以如: :id :style 等。由于对 vue 还不是太熟,记录下这个问题。