Table of Contents
Component instance" >Component instance
Download it locally, don’t change anything, and put it in the specified location. " >Download it locally, don’t change anything, and put it in the specified location.
Usage is the same as Vue" > Usage is the same as Vue
vant-weapp库中的popup样式设置" >vant-weapp库中的popup样式设置
vant-tree-select事件触发" >vant-tree-select事件触发
props获取不到" >props获取不到
驼峰式命名的事件无法触发[微信小程序]" >驼峰式命名的事件无法触发[微信小程序]
定制echarts,引入报错" >定制echarts,引入报错
getState()获取Store存储的数据" >getState()获取Store存储的数据
真机调试正常,预览/体验版空白(只有tabbar)" >真机调试正常,预览/体验版空白(只有tabbar)
获取路由参数" >获取路由参数
使用Taro/微信小程序同步接口,仍异步返回结果" >使用Taro/微信小程序同步接口,仍异步返回结果
分包" >分包
包大小限制" >包大小限制
分包操作" >分包操作
伪动态绑定事件" >伪动态绑定事件
获取组件实例" >获取组件实例
styleIsolation:  "apply-shared"
Home WeChat Applet Mini Program Development First experience in WeChat mini program development

First experience in WeChat mini program development

Jun 20, 2020 am 10:18 AM
taro WeChat applet

Component instance

this.selectComponent('.classSelector')

##Introduction

Taro

Vant Weapp is introduced in Taro and cannot be called directly through the third-party NPM package.

You need to perform the following steps:

    Find the Vant-weapp download file package on github and copy the corresponding
  • dist directory Go to the project/src/components/vant-weapp directory.
  • In
  • config.usingComponents of the Pages corresponding file, configure the components required for each page. (The so-called global registration of components cannot be done in app.js.)
  config = {
    navigationBarTitleText: '首页',
    usingComponents: {
      "van-button": "../../components/vant-weapp/button/index",
      "van-popup": "../../components/vant-weapp/popup/index"
    }
  }
Copy after login
    After using the
  • Vant-weapp component, taro The build will automatically copy the corresponding components to dist/components, and Vant-weapp’s components also depend on the tool library/src/components/vant-weapp/wxs, the tool library taro will not be automatically copied to dist. Therefore, we need to modify the config.copy.patterns in the /config/index.js file so that it will be automatically copied to the dist corresponding directory during compilation. Down.
  copy: {
    patterns: [
      {
        from: 'src/components/vant-weapp/wxs/',
        to: 'dist/components/vant-weapp/wxs/'
      }
    ],
    options: {
    }
  },
Copy after login
    Since the unit used in the style of
  • Vant-weapp is px, it will be compiled into # by taro ##rpx to adapt each device. You can prevent unit conversion by modifying config.weapp.module.pxtransform.selectorBlackList in the /config/index.js file.
    pxtransform: {
      enable: true,
      config: {
    
      },
      selectorBlackList: [
        /^.van-.*?$/,  // 这里是vant-weapp中className的匹配模式
      ]
    },
    Copy after login
ec-canvas

##ec-canvas

is the WeChat applet version of
ECharts. iconfont

Download it locally, don’t change anything, and put it in the specified location.

This resource will not be automatically copied to the

dist/

folder, so it needs to be copied by modifying the configuration file.

  copy: {
    patterns: [
      ...
      {
        from: 'src/assets/fonts/',
        to: 'dist/assets/fonts/'
      },
      ...
    ],
    options: {
    }
  }
Copy after login
Then, in the app.js entry file,

import './assets/fonts/iconfont.css'. Custom component

Component passing parameters to the outside

this.triggerEvent(
  'eventType',
  {
    key: value, //这里定义的键值对,在父组件中,通过args.detail.key获取;
  },
  {
    bubbles: true, //事件属性:是否冒泡;
    capturePhase: true, //事件属性: 是否可捕获;
  }
)
Copy after login
Slot

Usage is the same as Vue

.
Note
: The style defined within the component for

slot will not work. The style of the structure passed in slot can only be defined at the location where the component is called. Development obstacles

#Taro

<span style="font-size: 14px;">Switch custom tabBar</span> When Tab (config.tabBar.custom = true in app.jsx

), it needs to be in the life cycle of the corresponding Tab page

componentDidShow:

if (typeof this.$scope.getTabBar === 'function' && this.$scope.getTabBar()) {
  this.$scope.getTabBar().setData({
    selected: 1
  })
}
Copy after login
Note that it is this.$scope.getTabBar

. The layer coverage problem caused by Canvas

canvas

is a native component created by the client, and the level of the native component is the highest , so no matter how
z-index is set, other components in the page cannot be placed on top of the native component. So, if canvas
and mask interaction exist at the same time,

canvas will be on the upper layer of the mask. Solution:

Wrap a layer of structure outside

canvas
    , and set the
  • canvas container through conditions (mask switch) The hidden attribute. Through
  • cover-view
  • ,

    cover-image custom components, cover-view through positioning and upgrading the level, you can prevent Covered by canvas. Because the native component inserted later can cover the previous native component, please note:

    Structurally,
      cover-view
    • must be in canvas followed by ; can be used to adjust the display order through flex
    • and
    • order. Only the outermost
    • cover-view supports position: fixed.
  • typeof

wx:If

statement, the

typeof operation cannot be used operator, the typeof operator cannot be used in {{}}, and can only be used in wxs. data initialization assignment

I don’t know when data is initialized, but when initializing data

, you cannot use

this Points to the current component instance (this is this === void 0), that is, data can only be initialized to a constant. When properties

or

methods are required to initialize data, it can only be passed ## in the life cycle attached #this.setDataUpdate the value of data. <p>而且,如果<code>data.fn = this.methodNamemethodName中如果调用了this引用,这时this指向的是data,所以需要使用data.fn = this.methodName.bind(this)

vant-weapp库中的popup样式设置

popup内容的大小不是由内容撑起来的,需要通过popup组件的custom-class定义一个类名,设置widthheight来定义内容的尺寸。

vant-tree-select事件触发

Taro中的代码风格类React,而vant-weapp库中的代码风格为wxmlwxs风格。React绑定事件是驼峰式,wxml绑定事件是使用-连字符分隔。

这就造成了Taro使用vant-tree-select组件时,onClickNavonClickItem不会被vant-tree-select识别,事件无法触发。

解决方案:对vant-tree-select进行二次封装,事件原始触发通过this.$triggerEvent传出驼峰式的事件类型,在Taro中调用。


目前vant-weapp0.5.20中,vant-tree-select不支持单选。

props获取不到

驼峰式命名的事件无法触发[微信小程序]

注意@tarojs/cli版本,如最初用的1.2.0版本就获取不到自定义组件传的参数,升级到最新版1.3.15就可以了。

注意@tarojs/cli版本,如最初用的1.2.0版本无法触发驼峰式命名的事件,升级到最新版1.3.15,使用onClick-nav形式绑定事件就可以了。

<span style="font-size: 14px;">Taro</span>编译器无法自动将用到组件的<span style="font-size: 14px;">.wxs</span>文件移动到<span style="font-size: 14px;">/dist</span>相应目录下

手动移动。

<span style="font-size: 14px;">微信开发者工具</span>中运行<span style="font-size: 14px;">Taro</span>代码,如果有<span style="font-size: 14px;">async/await</span>,则regenerator is not defined。

微信开发者工具--> 右上角详情--> 本地设置里的配置全部关掉,如ES6转ES5...。

定制echarts,引入报错

echarts.js不需要再次编译,配置中新增编译时忽略echarts.js

weapp: {
    ...
    compile: {
      exclude: ['src/echarts-for-weixin/ec-canvas/echarts.js']
    }
}
Copy after login

getState()获取Store存储的数据

可以在<span style="font-size: 14px;">(dispatch, getState) => {</span>中使用。

真机调试正常,预览/体验版空白(只有tabbar)

将"本地设置"--> "上传时进行代码保护"取消勾选。

<span style="font-size: 14px;">Taro</span><span style="font-size: 14px;">className=''</span>单引号赋值不起作用。

className的值使用双引号包裹。

<span style="font-size: 14px;">Taro</span>自定义组件内部使用<span style="font-size: 14px;">iconfont</span>,不显示图标

参照外部样式类、全局样式类。
或者,组件单独引入iconfont.css也可以。

获取路由参数

this.$router.params

<span style="font-size: 14px;">iconfont</span>字符串渲染

如果将字体做变量使用,通用情况下无法正常显示。

  • 需要将icon: ['&#xe61d;', '&#xe62c;']改写成icon: ['\ue61e', '\ue62d']
  • <rich-text nodes={&#xe61e;}></rich-text>

使用Taro/微信小程序同步接口,仍异步返回结果

如使用Taro.getStorageSync('key')获取缓存数据,结果仍是异步返回。同步接口需要结合await使用,才是真正的同步。

分包

包大小限制

  • 包超过2048KB,无法上传

分包操作

  • 主包不需要特殊处理。

    • navigateTab导航的页面必须在主包中。
  • 分包

    • 分包在subPackages配置。
    pages: [
      'pages/login/login',
      'pages/index/index',
      'pages/manage/manage',
      'pages/schedule/schedule',
      'pages/inpidual/inpidual'
    ],
    'subPackages': [
      {
         'root': 'pages-main',
         name: 'main',
          'pages': [
            'acs/acs',
            'acs-setting/acs-setting',
            'setting-details/setting-details',
            'current-energy/current-energy',
            'history-energy/history-energy',
            'electricity/electricity',
            'runtime/runtime',
            'daily-usage/daily-usage',
            'onshift-record/onshift-record',
            'schedule-details/schedule-details'
        ]
      },
    ],
Copy after login

伪动态绑定事件

// index.wxml
<input
    wx:if="{{metas.type == &#39;text&#39; || metas.type == &#39;number&#39; || metas.type == &#39;idcard&#39; || metas.type == &#39;digit&#39;}}"
    name="{{metas.name}}"
    type="{{metas.type}}"
    value="{{value}}"
    placeholder="{{metas.attrs.placeholder}}"
    bindchange="{{changeValidate}}"
    bindinput="{{inputValidate}}"
    bindblur="{{blurValidate}}"
/>
Copy after login
// index.js

Component({
    data: {
        changeValidate: '',
        inputValidate: '',
        blurValidate: '',
        eventType: 'input',
        rules: '',
        value: '',
        isRequired: false,
        validateState: '', //['validating', 'success', 'error']
        validateMessage: ''
    },
    observers: {
        rules(newV) {
            console.log('------=======')
            this.setData({
                [`${this.data.eventType}Validate`]: 'onBlurValidate'
            })
        }
    },
    methods: {
        onBlurValidate (e) {
            this.onValidate(e, rule)
        },
        onValidate (e, rule) {

        }
    }
})
Copy after login

获取组件实例

refFormItem =  (node, idx) => {
    if(this.formItem) {
        !this.formItem.includes(node) &&    this.formItem.push(node)
    } else {
        this.formItem = [node]
    }
}
...
clearValidate  () {
    console.log(this.formItem)
    this.formItem.forEach(item => {
        item.clearValidate()
    })
}
...
render  () {
    const { fieldMetas } = this.props;
    return (
        <Form  className="form"  onSubmit={this.submitForm.bind(this)}>

        {

            fieldMetas.map((meta, idx) => {

                return (
                    <form-item  ref\={this.refFormItem} onValidate={this.gatherValidate.bind(this)} taroKey={meta.name} metas={meta} initialValue={this.findValue.call(this, meta.name)}>
                    </form-item>
                )
            })
        }
            <Button  form-type="submit">按钮</Button>
            <Button  onClick={this.clearValidate}>按钮</Button>
        </Form>
    )
}
Copy after login

styleIsolation:  "apply-shared"

对于options.styleIsolation =  "apply-shared"的应用:
如果是组件包裹组件,内部组件设置该配置,外部组件的样式依旧无法影响内部组件,Page()或Component()注册的页面级的样式才能影响到组件内部样式

推荐教程:《微信小程序

The above is the detailed content of First experience in WeChat mini program development. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Xianyu WeChat mini program officially launched Xianyu WeChat mini program officially launched Feb 10, 2024 pm 10:39 PM

Xianyu's official WeChat mini program has quietly been launched. In the mini program, you can post private messages to communicate with buyers/sellers, view personal information and orders, search for items, etc. If you are curious about what the Xianyu WeChat mini program is called, take a look now. What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3. If you want to use it, you must activate WeChat payment before you can purchase it;

WeChat applet implements image upload function WeChat applet implements image upload function Nov 21, 2023 am 09:08 AM

WeChat applet implements picture upload function With the development of mobile Internet, WeChat applet has become an indispensable part of people's lives. WeChat mini programs not only provide a wealth of application scenarios, but also support developer-defined functions, including image upload functions. This article will introduce how to implement the image upload function in the WeChat applet and provide specific code examples. 1. Preparatory work Before starting to write code, we need to download and install the WeChat developer tools and register as a WeChat developer. At the same time, you also need to understand WeChat

Implement the drop-down menu effect in WeChat applet Implement the drop-down menu effect in WeChat applet Nov 21, 2023 pm 03:03 PM

To implement the drop-down menu effect in WeChat Mini Programs, specific code examples are required. With the popularity of mobile Internet, WeChat Mini Programs have become an important part of Internet development, and more and more people have begun to pay attention to and use WeChat Mini Programs. The development of WeChat mini programs is simpler and faster than traditional APP development, but it also requires mastering certain development skills. In the development of WeChat mini programs, drop-down menus are a common UI component, achieving a better user experience. This article will introduce in detail how to implement the drop-down menu effect in the WeChat applet and provide practical

Implement image filter effects in WeChat mini programs Implement image filter effects in WeChat mini programs Nov 21, 2023 pm 06:22 PM

Implementing picture filter effects in WeChat mini programs With the popularity of social media applications, people are increasingly fond of applying filter effects to photos to enhance the artistic effect and attractiveness of the photos. Picture filter effects can also be implemented in WeChat mini programs, providing users with more interesting and creative photo editing functions. This article will introduce how to implement image filter effects in WeChat mini programs and provide specific code examples. First, we need to use the canvas component in the WeChat applet to load and edit images. The canvas component can be used on the page

Use WeChat applet to achieve carousel switching effect Use WeChat applet to achieve carousel switching effect Nov 21, 2023 pm 05:59 PM

Use the WeChat applet to achieve the carousel switching effect. The WeChat applet is a lightweight application that is simple and efficient to develop and use. In WeChat mini programs, it is a common requirement to achieve carousel switching effects. This article will introduce how to use the WeChat applet to achieve the carousel switching effect, and give specific code examples. First, add a carousel component to the page file of the WeChat applet. For example, you can use the &lt;swiper&gt; tag to achieve the switching effect of the carousel. In this component, you can pass b

What is the name of Xianyu WeChat applet? What is the name of Xianyu WeChat applet? Feb 27, 2024 pm 01:11 PM

The official WeChat mini program of Xianyu has been quietly launched. It provides users with a convenient platform that allows you to easily publish and trade idle items. In the mini program, you can communicate with buyers or sellers via private messages, view personal information and orders, and search for the items you want. So what exactly is Xianyu called in the WeChat mini program? This tutorial guide will introduce it to you in detail. Users who want to know, please follow this article and continue reading! What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3.

Implement the sliding delete function in WeChat mini program Implement the sliding delete function in WeChat mini program Nov 21, 2023 pm 06:22 PM

Implementing the sliding delete function in WeChat mini programs requires specific code examples. With the popularity of WeChat mini programs, developers often encounter problems in implementing some common functions during the development process. Among them, the sliding delete function is a common and commonly used functional requirement. This article will introduce in detail how to implement the sliding delete function in the WeChat applet and give specific code examples. 1. Requirements analysis In the WeChat mini program, the implementation of the sliding deletion function involves the following points: List display: To display a list that can be slid and deleted, each list item needs to include

Implement image rotation effect in WeChat applet Implement image rotation effect in WeChat applet Nov 21, 2023 am 08:26 AM

To implement the picture rotation effect in WeChat Mini Program, specific code examples are required. WeChat Mini Program is a lightweight application that provides users with rich functions and a good user experience. In mini programs, developers can use various components and APIs to achieve various effects. Among them, the picture rotation effect is a common animation effect that can add interest and visual effects to the mini program. To achieve image rotation effects in WeChat mini programs, you need to use the animation API provided by the mini program. The following is a specific code example that shows how to

See all articles