当前位置:网站首页>Wechat applet - simple diet recommendation (3)

Wechat applet - simple diet recommendation (3)

2022-07-05 09:55:00 Sunqk5665

This article is my article Simple diet recommendations ( One ) In function realization Turntable meal selection module .

Custom turntable assembly reference article :https://blog.csdn.net/qq_23375733/article/details/81274955

1、 Introduction to the random catering function of the turntable :

This module mainly uses small programs , Support customization of simple components , Use simple component-based programming supported by applets , Through this function, the design of turntable is realized . Then through the turntable , Realize random selection , Choose your meal today , Catering is through scientific diet , To serve you , The results of the catering will be displayed , If you are not satisfied , You can also choose this meal again .

2、 Module creativity

In this module , The creative points are as follows :
The creative point is in the form of turntable , To achieve the random choice of catering , It is not only possible to choose meals at one time , You can still achieve , Choose... Again , Choose the final one .
Another creative point is to use the custom components of wechat applet , The customization module of wechat applet is a way for developers to customize , Developers can abstract the function modules in the page into custom components , In order to reuse in different pages ; You can also split a complex page into multiple low coupling modules , Helps code maintenance . The custom component is very similar to the basic component when used .

3、 Design thinking

To complete this module and realize the corresponding functions of dish identification , The following problems must be solved :

  • Implementation of custom components
  • Use custom components
  • Rotary table rotation is realized through components
  • Return to catering
  • Display catering data
  • Overall interface design

4、 Implementation process

4.1 Use custom components

After searching for relevant information , Learned that wechat applets can use custom components , Custom components are a custom way for wechat developers , You can abstract the function modules in the page into custom components , In order to reuse in different pages ; You can also split a complex page into multiple low coupling modules , Helps code maintenance . The custom component is very similar to the basic component when used .

4.2 How to use custom components

Create custom components ( Official custom component development documentation ): Similar to page , A custom component consists of json wxml wxss js 4 Files make up . To write a custom component , The first thing you need to do is json File for custom component declaration ( take component Field set to true This set of files can be set as custom components ):

{
    
  "component": true
}

meanwhile , Still in wxml Write component template in file , stay wxss Add component styles... To the file , They are written in a similar way to the way pages are written .

<!--  This is the inside of the custom component WXML structure  --> <view class="inner">
  {
    {
    innerText}}
</view>
<slot></slot>
/*  The style here only applies to this custom component  */
.inner {
    
  color: red;
}

In the custom component of js In file , Need to use Component() To register components , And provide the property definition of the component 、 Internal data and custom methods .
The property values and internal data of the component will be used for the component wxml Rendering of , among , Property values can be passed in from outside the component .

Component({
    
  properties: {
    
    //  It's defined here innerText attribute , Property values can be specified when the component is used 
    innerText: {
    
      type: String,
      value: 'default value',
    }
  },
  data: {
    
    //  Here are some component internal data 
    someData: {
    }
  },
  methods: {
    
    //  Here is a custom method 
    customMethod: function(){
    }
  }
})

Before using registered custom components , First of all, on the page json Make a reference statement in the document . At this time, you need to provide the tag name of each custom component and the corresponding custom component file path :

{
    
  "usingComponents": {
    
    "component-tag-name": "path/to/the/custom/component"
  }
}

such , On page wxml You can use custom components just like basic components . The node name is the tag name of the custom component , The node property is the property value passed to the component .

4.3 Write custom components of the turntable

Write through wechat applet development documents , Custom components of turntable , Because this is the first time to write custom components , So I'm not familiar with the process , So there are many problems when using , And the idea went wrong , By using online tutorials , By reading someone else's code , Change writing code , The customization of components has been successfully realized .
The color of the first row turntable , Treatment of appearance , Use fan-shaped processing , Color is through JS The document defines .

<view animation="{
     {animationData}}" class="gb-wheel-content" style='width:{
       {
       size.w}}rpx;height:{
       {
       size.h}}rpx;'>
      <!--  Fan colored background   When the option length is equal to 2 perhaps 3 Special treatment was made during  -->
      <view class="canvas-list">
         <view class="canvas-item2" wx:for="{
     {awardsConfig.awards}}" wx:key="key" style="transform: rotate({
       {
       item.item2Deg}});background-color:{
       {
       awardsConfig.awards.length==2?item.color:''}};opacity:{
       {
       awardsConfig.awards.length==2?item.opacity:awardsConfig.awards.length==3?item.opacity:''}};width:{
       {
       size.h}}rpx;height:{
       {
       size.h/2-2}}rpx;transform-origin:{
       {
       size.h/2}}rpx {
       {
       size.h/2}}rpx">
            <view class="canvas-item2-after" style="transform: rotate({
       {
       item.afterDeg}});background-color:{
       {
       item.color}};opacity:{
       {
       awardsConfig.awards.length==3?'':item.opacity}};width:{
       {
       size.h/2}}rpx;height:{
       {
       size.h/2}}rpx;transform-origin: {
       {
       size.h/2}}rpx {
       {
       size.h/2}}rpx"></view>
            <view wx:if='{
     {awardsConfig.awards.length==3}}' class="canvas-item2-after" style="background-color:{
       {
       item.color}};width:{
       {
       size.h/2}}rpx;height:{
       {
       size.h/2}}rpx;transform-origin: {
       {
       size.h/2}}rpx {
       {
       size.h/2}}rpx"></view>
         </view>
      </view>


Then deal with the options :

<!--  Options content  -->
      <view class="gb-wheel-list">
         <view class="gb-wheel-item" data-index="{
     {index}}" wx:for="{
     {awardsConfig.awards}}" wx:key='key'>
            <view class="gb-wheel-icontent" style="height:262rpx;overflow:hidden;font-size:{
       {
       item.name.length>9?'20':'26'}}rpx;line-height:{
       {
       item.name.length>9?'20':'26'}}rpx;width:26rpx;padding-top:5rpx;transform: rotate({
       {
       index*turnNum}}turn);transform-origin: 50% {
       {
       size.h/2-2}}rpx">
               <text style='word-break:break-all;'>{
   {item.name}}</text>
            </view>
         </view>
      </view>
   </view>


Then the style processing of the middle start key :

<!--  The button in the middle of the turntable  -->
   <image bindtap="_zhuan" src='/images/canvas_button_go_unclick.png' style='width:{
       {
       size.h/4.4}}rpx;position:absolute;left:41%;top:38%;margin-top:-11rpx;z-index:9999;display:{
       {
       block1}}' mode='widthFix'></image>
   <image src='/images/canvas_button_go_click.png' style='width:{
       {
       size.h/4.4}}rpx;position:absolute;left:41%;top:38%;margin-top:-11rpx;z-index:9999;display:{
       {
       block2}}' mode='widthFix'></image>
   <image bindtap="reset" src='/images/canvas_button_reset_unclick.png' style='width:{
       {
       size.h/4.4}}rpx;left:41%;top:38%;position: absolute;margin-top:-11rpx;z-index:9999;display:{
       {
       block3}}' mode='widthFix'></image>
   <image src='/images/canvas_button_reset_click.png' style='width:{
       {
       size.h/4.4}}rpx;position:absolute;left:41%;top:38%;margin-top:-11rpx;z-index:9999;display:{
       {
       block4}}' mode='widthFix'></image>

And then in JS The definition of component attributes is implemented in the file. The attribute list of the component is used for component custom settings External properties of components , This can be achieved when calling components , The style has changed , Length and width , Color , Even the turning probability of the turntable .

properties: {
    
      myProperty: {
        //  Property name  myProperty2: String,  A simplified way to define 
         type: String, //  type ( Required ), The current types of acceptance include :String, Number, Boolean, Object, Array, null( Represents any type of )
         value: '',    //  Property default   Initial value ( Optional ), If it is not specified, it will select one... According to the type 
         observer: function (newVal, oldVal, changedPath) {
    
            //  The function executed when the property is changed ( Optional ), It can also be written in methods The method name string defined in the section ,  Such as :'_propertyChange'
            //  Usually  newVal  Is the newly set data , oldVal  It's old data 
         }
      },

      probability: {
    
         type: Boolean, //  Probability switch , Default random  false
         value: false
      },

      musicflg: {
    
         type: Boolean, //  Turntable sound switch , Default true
         value: true
      },

      fastJuedin: {
    
         type: Boolean, //  The switch that turns the turntable quickly , Default false
         value: false
      },

      repeat: {
    
         type: Boolean, //  Repeat the extraction switch , Default false
         value: false
      },

      size: {
    
         type: Object, //  Turntable size , Width height unit rpx
         value: {
    
            w: 659, //  Note that width is smaller than height 1rpx
            h: 660
         }
      },

      zhuanpanArr: {
     //  Turntable options that can be switched ,  Support multiple 
         type: Array,
         value: [
            {
    
               id: 0,
               option: ' Title name of the turntable ',
               awards: [
                  {
    
                     id: 0,
                     name: " most 17 An option ", //  Option name 
                     color: 'red',        //  Background color of options 
                     probability: 0       //  probability 
                  },
                  {
    
                     id: 1,
                     name: " Options can be filled in at most 13 word ", //  exceed 9 The font will become smaller when you write two words 
                     color: 'green',
                     probability: 0
                  }
               ],
            }
         ]
      },

      //  Limit : most 17 An option ,  A single option can be filled in at most 10-13 A word ,  The maximum number of option names 21 A word 
      awardsConfig: {
     //  Default current turntable options  
         type: Object,
         value: {
    
            option: ' My little decision ?',
            awards: [
               {
    
                  id: 0,
                  name: " most 17 An option ",
                  color: 'red',
                  probability: 0
               },
               {
    
                  id: 1,
                  name: " Options can be filled in at most 13 word ",
                  color: 'green',
                  probability: 0
               }
            ],
         }
      }

   },


Define the turntable animation :

data: {
    
      id: '',
      animationData: {
    }, //  Turntable animation 
      zhuanflg: false,   //  Whether the rotary table can click the switch flag 
      fastTime: 7600,    //  The time when the turntable rotates rapidly 
      slowTime: 3900,    //  The time when the turntable rotates slowly 
      block1: 'block',   //  The picture flag in the center of the turntable , Used to show hidden 
      block2: 'none',
      block3: 'none',
      block4: 'none',
   },

Then use the component life cycle , Pay attention to Create What cannot be used in the life cycle setDate,
Then, carry out various definitions and settings of the turntable , The button in the middle of the turntable starts to rotate , After the rotation is completed, return the data , Rotate reset , Then the position of the turntable changes randomly .

4.4 Use customized turntable components

The above is for customized components , Just for the following use . First , On the page where the component is to be referenced json In file , write :

{
    
  "usingComponents": {
    
    "zhuanpan":"/components/zhuanpan/zhuanpan" // Directory of your custom components 
  }
}

And then it's in WXML The interface references these components , The data that must be used in the reference process is size,myData,myAwars,startZhuan,zhuanpanArr,awardsConfig, With these, you can define the data on the turntable , How much data of the turntable , Rewriting of events after the turntable turns , The event occurs after the turntable stops .

<!--index.wxml-->
<view >
  <view class="title">
     What are you going to eat today ?
  </view>
  <view class="title"> I'll tell you .....</view>
 
<!--  Refer to the component ↓↓↓ -->
<zhuanpan id='zhuanpan' bind:myData='getData' bind:myAwards="getAwards" bind:startZhuan="startZhuan" size='{
     {size}}' musicflg='{
     {musicflg}}' fastJuedin='{
     {fastJuedin}}' repeat='{
     {repeat}}' zhuanpanArr='{
     {xiaojuedingArr}}' awardsConfig='{
     {awardsConfig}}'></zhuanpan>
<!--  Refer to the component ↑↑↑ -->
<view class="title">{
   {s_awards}}</view>
<view class="liebiao"> Catering list :
  <text>\n{
   {liebiao}}</text>
</view>
</view>


Write the data of the turntable ,

data: {
    
      size:{
     // The size of the turntable can be configured 
         w:599,
         h:600
      },// Turntable size ,
      musicflg: true, // voice 
      fastJuedin: false,// Make a quick decision 
      repeat: false,// Do not repeat extraction 
      probability: false,//  probability 
      s_awards: '?',// result 
      option: ' title ',
      id:'?',
      liebiao:'',
      // Total data of turntable , If you want to add more than one, you can add a piece of data with the same format to this array 
      xiaojuedingArr: [
         {
    
            id: 0,
            option: '',// Title name of the turntable 
            awards: [
               {
    
                  id: 0,                // id Increasing 
                  name: " Food match 1",           //  Option name   exceed 9 The font will become smaller when you write two words   Greater than 13 The number will hide the excess 
                  color: '#FFA827',    //  Background color of options 
                  probability: 10       //  probability  0 The representative will never turn to this option , The larger the number, the greater the probability ,data Medium probability Property is set to true Only when it comes into effect ,  This attribute must also be filled , If you don't fill in, you will make an error 
               },
               {
    
                  id: 1,
                  name: " Food match 2",
                  color: '#AA47BC',
                  probability: 10
               },
               {
    
                  id: 2,
                  name: " Food match 3",
                  color: '#42A5F6',
                  probability: 10
               }
      ],

Then there is the writing and calling of events .
Receive the data from the initialization of the turntable ,

getData(e) {
    
      this.setData({
    
         option: e.detail.option
      })
   },

Receive the answer option after the end of the current turntable , For a data transmission after the completion of the turntable , Show the list of the table and table you choose .

getAwards(e) {
    
      this.setData({
    
         liebiao:lie[e.detail.id],
         s_awards: e.detail.end ? "?" : e.detail.s_awards,
         // id:e.detail.id,
         
      })
   },

At the beginning or end of rotation , The occurrence of the incident .( There are some codes used in the experiment , Was noted out )

startZhuan(e) {
    
      
      // if(f == 0){
    
      // a = Math.floor(Math.random()*7)
      // console.log(a)
      // f = 1
      // }else{
    
      // f = 0
      // }
      this.setData({
    
         zhuanflg: e.detail ? true : false
      })
   },


Event to reset the turntable , An event called when using the reset turntable occurs , Switch the turntable , Reset the order of the turntable .

switchZhuanpan(e) {
    
      // Switch the turntable only when the turntable stops 
      if (!this.data.zhuanflg) {
    
         var idx = e.currentTarget.dataset.idx, zhuanpanArr = this.data.zhuanpanArr, obj = {
    };
         for (let i in zhuanpanArr) {
    
            if (this.data.option != zhuanpanArr[i].option && zhuanpanArr[i].id == idx) {
    
               obj.option = zhuanpanArr[i].option;
               obj.awards = zhuanpanArr[i].awards;
               this.setData({
    
                  awardsConfig: obj // In fact, by default, if you want to change the data of the current turntable, you need to transfer this object , It works 
               })
               break;
            }
         }
      }
   },


Another important thing is , For instantiation of component objects , Without instantiation, the use of component objects cannot be realized , So I instantiate this component object , Write directly into OnLoad In the life cycle , This enables the instantiation of component objects in the process of applet loading

onLoad: function () {
    
       // Instantiate component objects , In this way, the methods in the component can be called when necessary 
       this.zhuanpan = this.selectComponent("#zhuanpan");
 
   }

4.5 The method of displaying the randomly selected catering list

The method used is a relatively simple way to use the data written in the component id Return , This function was not written at the beginning , In the previous custom component , So I added this later id Return , Data transferred by the turntable , Return the id. Below r This is the return id, Before using random numbers , Produced , Returned the result , But not back id, Lead to later use id Can't call , So I added a id Return .

 that.setData({
    
               animationData: {
    },
               s_awards: awardsConfig.awards[r].name,// The final selected result 
               awardsConfig: awardsConfig,
               id:r,
               block1: 'none',
               block2: 'none',
               block3: 'block',
               zhuanflg: false,
            })

Then through the return id, To call the catering retrieved from the global data ,

// Receive the answer option after the end of the current turntable 
   getAwards(e) {
    
      this.setData({
    
         liebiao:lie[e.detail.id],// Call up the list of catering 
         s_awards: e.detail.end ? "?" : e.detail.s_awards,
         // id:e.detail.id,
         
      })
   },

5、 Overall appearance design

5.1 Design of turntable

This part wxml The key codes are as follows

<view animation="{
     {animationData}}" class="gb-wheel-content" style='width:{
       {
       size.w}}rpx;height:{
       {
       size.h}}rpx;'>
      <!--  Fan colored background   When the option length is equal to 2 perhaps 3 Special treatment was made during  -->
      <view class="canvas-list">
         <view class="canvas-item2" wx:for="{
     {awardsConfig.awards}}" wx:key="key" style="transform: rotate({
       {
       item.item2Deg}});background-color:{
       {
       awardsConfig.awards.length==2?item.color:''}};opacity:{
       {
       awardsConfig.awards.length==2?item.opacity:awardsConfig.awards.length==3?item.opacity:''}};width:{
       {
       size.h}}rpx;height:{
       {
       size.h/2-2}}rpx;transform-origin:{
       {
       size.h/2}}rpx {
       {
       size.h/2}}rpx">
            <view class="canvas-item2-after" style="transform: rotate({
       {
       item.afterDeg}});background-color:{
       {
       item.color}};opacity:{
       {
       awardsConfig.awards.length==3?'':item.opacity}};width:{
       {
       size.h/2}}rpx;height:{
       {
       size.h/2}}rpx;transform-origin: {
       {
       size.h/2}}rpx {
       {
       size.h/2}}rpx"></view>
            <view wx:if='{
     {awardsConfig.awards.length==3}}' class="canvas-item2-after" style="background-color:{
       {
       item.color}};width:{
       {
       size.h/2}}rpx;height:{
       {
       size.h/2}}rpx;transform-origin: {
       {
       size.h/2}}rpx {
       {
       size.h/2}}rpx"></view>
         </view>
      </view>

Here is the fan-shaped design of the turntable , Can pass JS File changes .

awards: [
            {
    
               id: 0,                // id Increasing 
               name: " Food match 1",           //  Option name   exceed 9 The font will become smaller when you write two words   Greater than 13 The number will hide the excess 
               color: '#FFA827',    //  Background color of options 
               probability: 10},


In this way, the implementation effect of this part is shown in the following figure :
 Insert picture description here

5.2 Middle button design

This part wxml The key codes are as follows

<!--  The button in the middle of the turntable  -->
   <image bindtap="_zhuan" src='/images/canvas_button_go_unclick.png' style='width:{
       {
       size.h/4.4}}rpx;position:absolute;left:41%;top:38%;margin-top:-11rpx;z-index:9999;display:{
       {
       block1}}' mode='widthFix'></image>
   <image src='/images/canvas_button_go_click.png' style='width:{
       {
       size.h/4.4}}rpx;position:absolute;left:41%;top:38%;margin-top:-11rpx;z-index:9999;display:{
       {
       block2}}' mode='widthFix'></image>
   <image bindtap="reset" src='/images/canvas_button_reset_unclick.png' style='width:{
       {
       size.h/4.4}}rpx;left:41%;top:38%;position: absolute;margin-top:-11rpx;z-index:9999;display:{
       {
       block3}}' mode='widthFix'></image>
   <image src='/images/canvas_button_reset_click.png' style='width:{
       {
       size.h/4.4}}rpx;position:absolute;left:41%;top:38%;margin-top:-11rpx;z-index:9999;display:{
       {
       block4}}' mode='widthFix'></image>

The icon is obtained from Alibaba vector icon library .
The effect is as follows .
 Insert picture description here

6、 Verification effect

Click on “GO”, The turntable began to turn .
 Insert picture description here
Select ,? Become a catering table , And the food came out .
 Insert picture description here
Click Reset button , The sequence is reset .
 Insert picture description here

原网站

版权声明
本文为[Sunqk5665]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140535206531.html