相信大家在開發(fā)的時候都會把項目中模塊相似的都會單獨做個組件,比如頭部搜索翎朱、列表橄维。。拴曲。等争舞,然后可以隨意的在需要的頁面中引入。這樣不僅簡化代碼澈灼,更方便維護(hù)竞川。今天我們看下在uni-app中如何簡單的創(chuàng)建組件并引用到頁面中。
上篇文章中講到了目錄中各個文件的用途蕉汪,components這個文件夾就是存放公共組件的地方流译。我們可以在這里面自行創(chuàng)建文件,接下來我們就拿列表來說下
在components文件中創(chuàng)建list文件者疤,
在這里插入圖片描述
創(chuàng)建list.vue文件后福澡,然后根據(jù)需求進(jìn)行編寫布局。我們來看下代碼驹马,(樣式我就不貼了):
<template name="listBox">
<view class="fallList">
<navigator class="fallBlock" v-for="(item , index) in fallList" :key="index" :url="`/pages/common/${item.fallUrl}`" id="item.id">
<image :src="item.fallImg" :mode="item.mode" class="fallImg">
<view class="mark">{{item.mark}}</view>
<view class="fallTitle">{{item.fallTitle}}</view>
<view class="fallFooter">
<view class="fallPortrait">
<image :src="item.fallPortrait" :mode="item.modes">
<text>{{item.fallName}}</text>
</view>
<view class="iconfont iconlike" :class="item.like"><text>{{item.likeViews}}</text></view>
<view class="iconfont iconSee" :class="item.see"><text>{{item.seeViews}}</text></view>
<view class="iconfont iconComment" :class="item.comment"><text>{{item.commentViews}}</text></view>
</view>
</navigator>
</view>
</template>
<script>
export default{
name:"listBox",
props:{
fallList:{
fallUrl:{
type: String,
default: ''
},
fallImg:{
type: String,
default: ''
},
mode:{
type: String,
default: ''
},
mark:{
type: String,
default: ''
},
fallTitle:{
type: String,
default: ''
},
fallPortrait:{
type: String,
default: ''
},
modes:{
type: String,
default: ''
},
fallName:{
type: String,
default: ''
},
see:{
type: String,
default: ''
},
seeViews:{
type: String,
default: ''
},
comment:{
type: String,
default: ''
},
commentViews:{
type: String,
default: ''
},
like:{
type: String,
default: ''
},
likeViews:{
type: String,
default: ''
}
}
},
data(){
return{
}
},
methods:{
}
}
</script>
根據(jù)上面的代碼革砸,我們可以看到在js中我們數(shù)據(jù)都存放在props里面了除秀。這樣我們的組件里面的代碼就算是完事了。接下來我們要在頁面中引入該組件算利。
<view class="listImg">
<listBox :fallList="fallList"></listBox>
</view>
<script>
import listBox from '@/components/fallList/list.vue'//這里就是在頁面中引入組件路徑的寫法
export default {
components:{
listBox //這里是組件中name名稱册踩,在import引入的時候名稱要一致
},
data() {
return {
fallList:[]//這里是列表組件獲取數(shù)據(jù)存放的地方
}
},
onLoad() {
this.placeData();//頁面加載獲取列表數(shù)據(jù)
},
methods: {
placeData(){ //獲取接口數(shù)據(jù)
uni.request({
url:'https://www.fastmock.site/mock/接口id/list/api/mineList',
method: 'POST',
dataType: 'JSON',
data:{
text:'uni.request'
},
header: {
'content-type': 'application/x-www-form-urlencoded'
},
success: (res) => {
console.log(res.data);
// 將請求到的數(shù)據(jù)存放放到listing中038354
this.fallList = eval(res.data);
}
});
}
}
}
</script>
以上就是簡單的講了下uni-app中如何創(chuàng)建組件并引入到頁面中,這里和小程序還是有點區(qū)別的效拭。
小程序中頁面引入組件如下:
<nav-bar navbar-data="{{nvabarData}}"></nav-bar>
nvabarData: {
showCapsule: 1, //是否顯示左上角圖標(biāo) 1表示顯示 0表示不顯示
title: '訂單查詢', //導(dǎo)航欄 中間的標(biāo)題
}
好了今天就寫到這了暂吉,有不足的地方歡迎大家評論指正。