欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

微信小程序云开发示例:数据库与云存储的结合运用

最编程 2024-01-09 09:15:59
...

已测试

业务:

图片等静态资源上传到小程序云存储,使用原生小程序语法调用、展示

一般的数据库读取、展示

一、模拟测试数据,静态数据测试+云开发基础配置

eg:

Page({
    data: {
        schools:[{
              name:'A',
              addr:'a市',
              imgUrl:'https://1.jpg'
        },{
              name:'B',
              addr:'b市' ,
              imgUrl: './images/3.jpg'
        }]        
    }
})

二、使用云存储+配置数据库

1、使用云存储

云开发-存储-(新建文件夹)school-上传1.jpg,此时会生成fileId,fileId格式为【固定的环境Id+文件目录+文件名】eg:

2、配置数据库

云开发-数据库-创建集合-(输入集合名称,即表名)imgs及schools-点击对应集合-记录列表 添加记录-添加 字段/类型/值-确定

按测试数据多输入几条

三、js+wxml

js>

Page({
    data: {
        schools:[]        
    },
    onLoad: function (options) {
        const db = wx.cloud.database();
        const _ = db.command;
        db.collection("imgs").where({
            purpose: 'swiper'
        }).get().then(res => {
            this.setData({
                imgs: res.data
            })
        });

        db.collection('schools').orderBy('name', 'desc').where({
            addr: _.neq("b市"),
        }).get().then(res => {
            this.setData({
                schools: res.data
            })
        });
    }
})

设置全局变量fileEnvId为云存储环境地址

//app.js
App({
  globalData: {
    fileEnvId:'cloud://cloud1-sdfaasdd.547a-cloud1-dfaasdd-156499'
  },

wxml>

<view>     
    <block wx:for="{{schools}}" wx:key="index" wx:for-item="school">
        <view class="school"  bindtap="navigate" data-addr='{{school.addr}}' ">
        <image class="school-img" src="{{fileEnvId}}{{school.imgUrl}}"></image>
        <view class="school-name">{{school.name}}</view>                          
     </block>
</view>