First experience in WeChat mini program development

hzc
Release: 2020-06-20 11:06:17
forward
3440 people have browsed it

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!

Related labels:
source:segmentfault.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template