【项目】uniapp前端接收后端springboot数据并渲染到界面+使用swiper和uView
兩個部分弄了很久,記錄過程:
request前后端交互
1.需要用到uni.request,記得先npm下載request(自己因為一開始沒有下載就寫代碼而折騰了好久也沒有成功發(fā)送請求)和uview-ui
自己現(xiàn)在下載了的依賴項:
下載了以后main.js:
import uView from “uview-ui”;
Vue.use(uView);
目錄:
pages:
{"easycom": {"^u-(.*)": "uview-ui/components/u-$1/u-$1.vue"},"pages": [ //pages數(shù)組中第一項表示應用啟動頁,參考:https://uniapp.dcloud.io/collocation/pages{"path": "pages/index/index","style": {"navigationBarTitleText": "一鍵洗滌"}},{"path": "pages/js/index","style": {"navigationBarTitleText": "設置"}},{"path": "pages/template/index","style": {"navigationBarTitleText": "數(shù)據(jù)查看"}},{"path": "pages/test/test","style": {"navigationBarTitleText": "測試"}}],"globalStyle": {"navigationBarTextStyle": "black","navigationBarTitleText": "uni-app","navigationBarBackgroundColor": "#F8F8F8","backgroundColor": "#F8F8F8"},"tabBar": {"color": "#909399","selectedColor": "#303133","backgroundColor": "#FFFFFF","borderStyle": "black","list": [{"pagePath": "pages/index/index","iconPath": "static/uview/example/component.png","selectedIconPath": "static/uview/example/component_select.png","text": "組件"},{"pagePath": "pages/js/index","iconPath": "static/uview/example/js.png","selectedIconPath": "static/uview/example/js_select.png","text": "工具"},{"pagePath": "pages/template/index","iconPath": "static/uview/example/template.png","selectedIconPath": "static/uview/example/template_select.png","text": "模板"}]}}接收后端數(shù)據(jù):
<view v-for="(user,index) in users" :key="index"><view style="color: #71D5A1;"><u-icon name="clock" color="#2979ff" size="28"></u-icon>{{user.time}}日清洗時長:{{user.lasttime}}分鐘</view><view><u-icon name="clock-fill" color="#2979ff" size="28"></u-icon>總清洗時間:{{user.alltime}}</view><hr></view><image class="logo" src="/static/wa2.png"></image><view class="text-area"><text class="title">{{title}}</text></view><script>export default {data() {return {users:[],title: '歷史清洗記錄',tabbar: '',list1: [{text: '水量耗費記錄',color: 'blue',fontSize: 28,subText: '查看'}, {text: '清洗時間記錄',color: 'green',fontSize: 28,subText: '查看'}, {text: '其他情況反饋' ,color: 'red',fontSize: 28,subText: '查看'}],show: false}},onLoad() {this.getUsers();this.tabbar = [{iconPath: "/static/uview/example/component.png",selectedIconPath: "/static/uview/example/component_select.png",text: '一鍵洗碗',count: 2,isDot: true,pagePath: "/pages/index/index"},{iconPath: "/static/uview/example/js.png",selectedIconPath: "/static/uview/example/js_select.png",text: '機器參數(shù)設置',midButton: true,pagePath: "/pages/js/index"},{iconPath: "/static/uview/example/template.png",selectedIconPath: "/static/wa.png",text: '歷史清洗記錄',pagePath: "/pages/template/index"},]},methods:{getUsers: function() {var _this= this;// 詳見官網(wǎng):https://uniapp.dcloud.io/api/request/requestuni.request({url:'http://localhost:9000/wash',method: 'GET',success: res => {_this.users = res.data.data;console.log(_this.users)},});console.log(22)}}} </script><style>.content {display: flex;flex-direction: column;align-items: center;justify-content: center;}.logo {height: 400rpx;width: 600rpx;margin-top: 50rpx;margin-left: auto;margin-right: auto;margin-bottom: 50rpx;}.text-area {display: flex;justify-content: center;}.title {font-size: 36rpx;color: #8f8f94;} </style>
后端用的是之前的springboot框架:
Mapper層:
service:
public interface WahService {List<Wash> allWash(); }@Service public class WashServiceImpl implements WahService{@AutowiredWashDao washDao;@Overridepublic List<Wash> allWash(){return washDao.findAll();} }controller:
@RestController public class WashController {@Autowiredprivate WashServiceImpl washService;@GetMapping("/wash")public ApiResult getWsah(){List<Wash>res = washService.allWash();return ApiResultHandler.buildApiResult(200,"查詢所有洗滌時間",res);} }連接數(shù)據(jù)庫并啟動后端
注意:用真機調(diào)試的話localhost換成局域網(wǎng)下的ip地址
用ipconfig -all查看ip地址
使用swiper:
<view class="u-swiper-wrap" :style="{borderRadius: `${borderRadius}rpx`}"><swiper :current="elCurrent" @change="change" @animationfinish="animationfinish" :interval="interval" :circular="circular" :duration="duration" :autoplay="autoplay":previous-margin="effect3d ? effect3dPreviousMargin + 'rpx' : '0'" :next-margin="effect3d ? effect3dPreviousMargin + 'rpx' : '0'":style="{height: height + 'rpx',backgroundColor: bgColor}"><swiper-item class="u-swiper-item" v-for="(item, index) in list" :key="index"><view class="u-list-image-wrap" @tap.stop.prevent="listClick(index)" :class="[uCurrent != index ? 'u-list-scale' : '']" :style="{borderRadius: `${borderRadius}rpx`,transform: effect3d && uCurrent != index ? 'scaleY(0.9)' : 'scaleY(1)',margin: effect3d && uCurrent != index ? '0 20rpx' : 0,}"><image class="u-swiper-image" :src="item[name] || item" :mode="imgMode"></image><view v-if="title && item.title" class="u-swiper-title u-line-1" :style="[{'padding-bottom': titlePaddingBottom}, titleStyle]">{{ item.title }}</view></view></swiper-item></swiper><view class="u-swiper-indicator" :style="{top: indicatorPos == 'topLeft' || indicatorPos == 'topCenter' || indicatorPos == 'topRight' ? '12rpx' : 'auto',bottom: indicatorPos == 'bottomLeft' || indicatorPos == 'bottomCenter' || indicatorPos == 'bottomRight' ? '12rpx' : 'auto',justifyContent: justifyContent,padding: `0 ${effect3d ? '74rpx' : '24rpx'}`}"><block v-if="mode == 'rect'"><view class="u-indicator-item-rect" :class="{ 'u-indicator-item-rect-active': index == uCurrent }" v-for="(item, index) in list":key="index"></view></block><block v-if="mode == 'dot'"><view class="u-indicator-item-dot" :class="{ 'u-indicator-item-dot-active': index == uCurrent }" v-for="(item, index) in list":key="index"></view></block><block v-if="mode == 'round'"><view class="u-indicator-item-round" :class="{ 'u-indicator-item-round-active': index == uCurrent }" v-for="(item, index) in list":key="index"></view></block><block v-if="mode == 'number'"><view class="u-indicator-item-number">{{ uCurrent + 1 }}/{{ list.length }}</view></block></view></view> <script>import swiper from "swiper";export default {props: {// 輪播圖的數(shù)據(jù),格式如:[{image: 'xxxx', title: 'xxxx'},{image: 'yyyy', title: 'yyyy'}],其中title字段可選list: {type: Array,default () {return [{image: '../../static/wa2.png'},{image: '../../static/wa3.png'},{image: '../../static/wa4.png'},{image: '../../static/wa9.png'}];}},// 是否顯示title標題title: {type: Boolean,default: false},// 用戶自定義的指示器的樣式indicator: {type: Object,default () {return {};}},// 圓角值borderRadius: {type: [Number, String],default: 8},// 隔多久自動切換interval: {type: [String, Number],default: 3000},// 指示器的模式,rect|dot|number|roundmode: {type: String,default: 'round'},// list的高度,單位rpxheight: {type: [Number, String],default: 900},// 指示器的位置,topLeft|topCenter|topRight|bottomLeft|bottomCenter|bottomRightindicatorPos: {type: String,default: 'bottomCenter'},// 是否開啟縮放效果effect3d: {type: Boolean,default: false},// 3D模式的情況下,激活item與前后item之間的距離,單位rpxeffect3dPreviousMargin: {type: [Number, String],default: 50},// 是否自動播放autoplay: {type: Boolean,default: true},// 自動輪播時間間隔,單位msduration: {type: [Number, String],default: 500},// 是否銜接滑動,即到最后一張時接著滑動,是否自動切換到第一張circular: {type: Boolean,default: true},// 圖片的裁剪模式 imgMode: {type: String,default: 'aspectFill'},// 從list數(shù)組中讀取的圖片的屬性名name: {type: String,default: 'image'},// 背景顏色bgColor: {type: String,default: '#f3f4f6'},// 初始化時,默認顯示第幾項current: {type: [Number, String],default: 0},// 標題的樣式,對象形式titleStyle: {type: Object,default() {return {}}}},watch: {// 如果外部的list發(fā)生變化,判斷長度是否被修改,如果前后長度不一致,重置uCurrent值,避免溢出list(nVal, oVal) {if(nVal.length !== oVal.length) this.uCurrent = 0;},// 監(jiān)聽外部current的變化,實時修改內(nèi)部依賴于此測uCurrent值,如果更新了current,而不是更新uCurrent,// 就會錯亂,因為指示器是依賴于uCurrent的current(n) {this.uCurrent = n;}},data() {return {uCurrent: this.current ,title: 'Hello Intelligent wash',tabbar: '',}},computed: {justifyContent() {if (this.indicatorPos == 'topLeft' || this.indicatorPos == 'bottomLeft') return 'flex-start';if (this.indicatorPos == 'topCenter' || this.indicatorPos == 'bottomCenter') return 'center';if (this.indicatorPos == 'topRight' || this.indicatorPos == 'bottomRight') return 'flex-end';},titlePaddingBottom() {let tmp = 0;if (this.mode == 'none') return '12rpx';if (['bottomLeft', 'bottomCenter', 'bottomRight'].indexOf(this.indicatorPos) >= 0 && this.mode == 'number') {tmp = '60rpx';} else if (['bottomLeft', 'bottomCenter', 'bottomRight'].indexOf(this.indicatorPos) >= 0 && this.mode != 'number') {tmp = '40rpx';} else {tmp = '12rpx';}return tmp;},// 因為uni的swiper組件的current參數(shù)只接受Number類型,這里做一個轉(zhuǎn)換elCurrent() {return Number(this.current);}},methods: {// 按鈕點擊listClick(index) {this.$emit('click', index);},change(e) {let current = e.detail.current;this.uCurrent = current;// 發(fā)出change事件,表示當前自動切換的index,從0開始this.$emit('change', current);},// 頭條小程序不支持animationfinish事件,改由change事件// 暫不監(jiān)聽此事件,因為不再給swiper綁定uCurrent屬性animationfinish(e) {// #ifndef MP-TOUTIAO// this.uCurrent = e.detail.current;// #endif}}} </script>效果:
附:
引入iview:
按需引用 #
借助插件 babel-plugin-import可以實現(xiàn)按需加載組件,減少文件體積。首先安裝,并在文件 .babelrc 中配置:
npm install babel-plugin-import --save-dev
// .babelrc
{
“plugins”: [[“import”, {
“l(fā)ibraryName”: “view-design”,
“l(fā)ibraryDirectory”: “src/components”
}]]
}
然后這樣按需引入組件,就可以減小體積了:
import { Button, Table } from ‘view-design’;
Vue.component(‘Button’, Button);
Vue.component(‘Table’, Table);
特別提醒 #
按需引用仍然需要導入樣式,即在 main.js 或根組件執(zhí)行 import ‘view-design/dist/styles/iview.css’;
組件使用規(guī)范 #
使用:prop傳遞數(shù)據(jù)格式為 數(shù)字、布爾值或函數(shù)時,必須帶:(兼容String除外,具體看組件文檔),比如:
Correct usage:
Incorrect usage:
在非 template/render 模式下(例如使用 CDN 引用時),組件名要分隔,例如 DatePicker 必須要寫成 date-picker。
以下組件,在非 template/render 模式下,需要加前綴 i-:
Button: i-button
Col: i-col
Table: i-table
Input: i-input
Form: i-form
Menu: i-menu
Select: i-select
Option: i-option
Progress: i-progress
Time: i-time
以下組件,在所有模式下,必須加前綴 i-,除非使用 iview-loader:
Switch: i-switch
Circle: i-circle
總結(jié)
以上是生活随笔為你收集整理的【项目】uniapp前端接收后端springboot数据并渲染到界面+使用swiper和uView的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【项目实战】vue+springboot
- 下一篇: html5 将资源存于客户端,HTML5