组件创建、组件注册方式
一、创建组件
1.在存放组件的目录下新建组件页面文件li-activity.vue文件,
<template name="li-activity"> <view class="li-group"> <view class="act-img-left"> <image :src="list.image" class="img" mode=""></image> <view class="share-num-icon" v-if="list.scan"> <text class="sha-num">{{list.scan}}</text> <text class="has-num">{{list.share}}</text> </view> </view> <view class="act-content-right"> <text class="title">{{list.title}}</text> <text class="subtitle">{{list.subtitle}}</text> <view class="bottom-content"> <text class="type">免费</text> <view class="button"> <view class="example tap-button" @tap="goExample(list.cates,list.id)">查看详情</view> <view class="creat tap-button" @tap="goCreat(list.cates,list.id)">创建</view> </view> </view> </view> </view> </template>
li-activity.vue 文件的组件相关配置:
<script> export default { name:'li-activity', props:{ list:{ type:Object, default:{} } }, methods:{ goExample:function(cate,id){ uni.navigateTo({ url: '/pages/activity-detail/'+ cate +'/'+ cate +'?id='+id }); }, goCreat:function(cate,id){ uni.navigateTo({ url:'/pages/activity-creat/'+ cate +'/'+ cate +'?id='+id }) } } } </script>
name为组件名称;props为相关动态控制的参数,在使用该组件时传递过来;methods为组件内绑定的相关事件
二、组件注册
2.1、全局组件注册
在main.js中引入该组件文件:
import liActivity from './pages/components/li-activity/li-activity.vue'
组件全局注册:
Vue.component('li-activity',liActivity);
然后便可以在其他文件中使用该组件,如在index.vue中使用组件:
<template> <view class="content"> <li-activity v-for="(item,index) in actlist" :key="index" :list="item"></li-activity> </view> </template> <script> export default { data() { return { cate:'', cid:'', page:'1', actlist:[] }; }, onLoad(e) { this.getList(1) }, methods:{ getList:function(page){} } } </script> <style> .content{ width: 100%; padding-left: 3%; padding-right: 3%; box-sizing: border-box; } </style>
2.2、局部组件注册
直接在需要使用组件的页面进行注册组件,如在index.vue中使用组件:
在index.vue中引入组件文件:
import liActivity from '../../components/li-activity/li-activity.vue'
并在该页面进行组件注册:
components:{ 'li-activity':liActivity },
然后便可以在其他文件中使用该组件,局部注册组件完整代码如下:
<template> <view class="content"> <li-activity v-for="(item,index) in actlist" :key="index" :list="item"></li-activity> </view> </template> <script> import liActivity from '../../components/li-activity/li-activity.vue' export default { data() { return { cate:'', cid:'', page:'1', actlist:[] }; }, components:{ 'li-activity':liActivity }, onLoad(e) { this.getList(1) }, methods:{ getList:function(page){} } } </script> <style> .content{ width: 100%; padding-left: 3%; padding-right: 3%; box-sizing: border-box; } </style>
转载时请注明出处及相应链接,本文永久地址:https://www.cnblogs.com/wangxiaoling/p/10173965.html,谢谢!