>  기사  >  위챗 애플릿  >  WeChat 미니 프로그램의 프레임워크 분석

WeChat 미니 프로그램의 프레임워크 분석

不言
不言원래의
2018-06-27 14:39:011593검색

본 글은 위챗 미니 프로그램 프레임워크에 대한 자세한 설명과 예시 애플리케이션에 대한 관련 정보를 주로 소개합니다. 도움이 필요한 친구가 참고할 수 있습니다.

미니 프로그램 프레임워크를 기반으로 개발된 할 일 앱인 위챗 미니 프로그램의 사용법을 빠르게 이해하세요.

WeChat은 WeChat 미니 프로그램에 대한 공식 문서와 개발자 도구를 공식적으로 공개했습니다. 지난 이틀 동안 작은 프로그램을 개발하는 방법을 이해하기 위해 관련 뉴스를 읽었습니다. 지난 이틀 동안 공식 문서가 나온 후 빠르게 살펴보고 문서의 두 부분인 프레임워크와 문서를 이해하는 데 집중했습니다. 그런 다음 간단한 튜토리얼을 기반으로 일반 할 일 앱을 만듭니다. 이 앱은 WeChat 애플릿 플랫폼을 기반으로 하며 todo 앱의 일반 기능을 구현하는 동시에 실제 작업 시나리오에 더 가깝게 만들기 위해 로딩 및 토스트 구성 요소를 사용하여 상호 작용 및 피드백을 완료합니다. 일부 작업 중. 이 플랫폼에 대한 나의 직관적인 느낌은 기술 수준에서 Vue와 유사하지만 개발 아이디어는 Vue와 같지 않고 백본과 비슷하다는 것입니다. 따라서 백본, vue 등 mvc, mvvm 프레임워크를 사용해 본 사람들은 이 플랫폼을 쉽게 시작할 수 있습니다. 이 글에서는 주로 이 Todo 앱 구현의 몇 가지 핵심 사항을 소개합니다.

먼저 이 기사와 관련된 정보를 추가하세요:

공식 문서: https://mp.weixin.qq.com/debug/wxadoc/dev/index.html

공식 개발자 도구 다운로드: https://mp. weixin.qq.com/debug/wxadoc/dev/devtools/download.html

이 기사의 할 일 앱 기능 데모:

참고: 직접 편집하려면 할 일 텍스트를 길게 눌러야 합니다. 휴대폰에서는 더블클릭 이벤트를 편집용으로 사용할 수 없고, 길게 누르기 이벤트로 변경하였습니다. 미니 프로그램 플랫폼은 더블 클릭 이벤트에 대한 바인딩도 제공하지 않습니다.

관련 소스 코드: https://github.com/liuyunzhuge/blog/tree/master/todos/wx

이 프로젝트를 로컬에서 실행하려면 먼저 개발자 도구를 설치해야 하며, 설명을 따르십시오. 문서에 있는 간단한 튜토리얼입니다. 먼저 프로젝트를 빌드합니다.
구성이 완료되면 개발자 도구가 프로젝트를 엽니다.
그런 다음 디스크에서 빌드된 프로젝트의 폴더를 찾아 내부 내용을 모두 삭제하고 모두 붙여넣기를 바꿉니다.
그런 다음 개발자 도구를 다시 열고 먼저 편집 탭으로 들어간 다음 컴파일 버튼을 클릭하면 디버깅 인터페이스로 직접 들어가 앱의 기능을 볼 수 있습니다.

이 앱의 개발 과정을 소개하겠습니다. 앱 핵심 사항:

1. 이 앱의 디렉터리 구조와 구성은 문서 프레임워크 섹션에서 자세히 설명하지 않습니다. 이 플랫폼에는 html과 css가 없으며 wxml과 wxss로 대체되었습니다. wxss와 CSS 사이에는 거의 차이가 없습니다. 단점은 CSS만큼 강력하지 않고 제한된 선택기를 지원한다는 것입니다. 하지만 장점은 위챗이라는 플랫폼 하나만 있기 때문에 호환성 문제가 거의 없고, 표준 및 업데이트된 CSS 기술을 사용할 수 있다는 점입니다. wxml에서는 플랫폼에서 제공하는 컴포넌트의 태그만 사용할 수 있으며, HTML 태그는 직접 사용할 수 없습니다. wxml의 각 컴포넌트를 사용하는 방법의 예는 문서 - 컴포넌트 섹션에서 확인할 수 있습니다. 그래서 실제로 wxml과 wxss를 작성하는데는 문제가 없습니다.

2.wxml은 다음 기능을 지원합니다.

템플릿과 참조를 제외하고 나머지는 모두 todo 앱에서 사용됩니다. 그러나 각 기능의 세부 사항은 앱의 적절한 기능에 따라 사용됩니다. 선택됩니다. 며칠 전 위챗 애플릿이 vue 프레임워크를 기반으로 구현될 수 있다는 기사를 보고 vue 문서를 살펴봤습니다. 데이터 바인딩, 조건부 렌더링, 목록 렌더링, 이벤트에 대해서는 vue의 사용법을 자세히 살펴보았습니다. 이에 비해 wxml에서 제공하는 기능은 vue의 관련 기능과 상당히 유사하지만, 기능이 그리 많지 않기 때문에 vue 프레임워크의 기능을 작은 프로그램에 직접 활용하기는 쉽지 않습니다. 모범 사례는 여전히 공식 문서에 제공된 지침을 기반으로 합니다. 공식 문서에 기능이 언급되지 않은 경우 추측하여 사용하면 확실히 작동하지 않습니다. 일부 객체의 프로토타입을 인쇄하여 확인해 보았는데, 공식 문서에서 나온 것보다 더 많은 인스턴스 메소드를 찾지 못했습니다. 이는 미니 프로그램의 프레임워크 기능이 실제로 제한되어 있음을 보여줍니다.

3. 선택기가 프레임워크의 요구 사항을 충족하는 한 Wxss는 실제로 less 또는 sass로 작성할 수 있습니다. 시간적 제약으로 인해 이 앱에서는 시도하지 않았습니다.

4. 양방향 바인딩이 없습니다. Vue에서 Vue 인스턴스는 뷰 모델입니다. 뷰 계층의 데이터 업데이트는 실시간으로 모델에 피드백됩니다. 미니 프로그램에는 양방향 바인딩이 없으며 뷰 업데이트가 모델에 직접 동기화되지 않습니다. 관련 이벤트 콜백의 뷰 레이어에서 직접 데이터를 가져온 다음 모델을 업데이트해야 합니다. setData를 통해 미니 프로그램은 미니 프로그램 내에서 setData를 사용합니다. 그런 다음 페이지를 다시 렌더링합니다. 예를 들어 단일 할 일 항목의 경우 전환 작업은

toggleTodo: function( e ) {

 var id = this.getTodoId( e, 'todo-item-chk-' );
 var value = e.detail.value[ 0 ];
 var complete = !!value;
 var todo = this.getTodo( id );

 todo.complete = complete;
 this.updateData( true );
 this.updateStorage();
},

입니다.

以上代码中,通过e.detail.value[0]拿到单个todo项里面checkbox的值,通过该值来判断todo的complete状态。最后在updateData的内部,还会通过setData方法,刷新model的内容。只有这样,在toggle操作之后,app底部的统计信息才会更新。

5. 事件绑定的时候,无法传递参数,只能传递一个event。比如上面那个toggle的操作,我其实很想在回调里面把当前todo的id传到这个回调里面,但是想尽办法都做不到,最后只能通过id的方式来处理:就是在wxml中绑定事件的组件上面,加一个id,这个id全page也不能重复,所以id得加前缀,然后在id最后加上todo的id值;当事件触发的时候,通过e.currentTarget.id就能拿到该组件的id,去掉相应的id前缀,就得到todo的id值了。这是目前用到的一个方法,我认为不是很优雅,希望后面能发现更好的办法来实现。

6. app中考虑到了loading的效果,要利用button组件的loading属性来实现。但是loading仅仅是一个样式的控制,它不会控制这个按钮是否能重复点击。所以还要利用buttong的disabled属性,防止重复点击。

剩下的实现细节,都在下面两个文件的源码中,欢迎大家指出其中的问题。

index.wxml的源码:

<!--list.wxml-->
<view class="container">
 <view class="app-hd">
  <view class="fx1">
   <input class="new-todo-input" value="{{newTodoText}}" auto-focus bindinput="newTodoTextInput"/> 
  </view>
  <button type="primary" size="mini" bindtap="addOne" loading="{{addOneLoading}}" disabled="{{addOneLoading}}"> 
  + Add
  </button>
 </view>
 <view class="todos-list" >
  <view class="todo-item {{index == 0 ? &#39;&#39; : &#39;todo-item-not-first&#39;}} {{todo.complete ? &#39;todo-item-complete&#39; : &#39;&#39;}}" wx:for="{{todos}}" wx:for-item="todo">
   <view wx-if="{{!todo.editing}}">
    <checkbox-group id="todo-item-chk-{{todo.id}}" bindchange="toggleTodo">
     <label class="checkbox">
      <checkbox value="1" checked="{{todo.complete}}"/>
     </label>
    </checkbox-group>
   </view>
   <view id="todo-item-txt-{{todo.id}}" class="todo-text" wx-if="{{!todo.editing}}" bindlongtap="startEdit">
    <text>{{todo.text}}</text>
   </view>
   <view wx-if="{{!todo.editing}}">
    <button id="btn-del-item-{{todo.id}}" bindtap="clearSingle" type="warn" size="mini" loading="{{todo.loading}}" disabled="{{todo.loading}}"> 
     Clear
    </button>
   </view>
   <input id="todo-item-edit-{{todo.id}}" class="todo-text-input" value="{{todo.text}}" auto-focus bindblur="endEditTodo" wx-if="{{todo.editing}}"/> 
  </view>
 </view>
 <view class="app-ft" wx:if="{{todos.length > 0}}">
  <view class="fx1">
   <checkbox-group bindchange="toggleAll">
    <label class="checkbox">
     <checkbox value="1" checked="{{todosOfUncomplted.length == 0}}"/>
    </label>
   </checkbox-group>
   <text>{{todosOfUncomplted.length}} left.</text>
  </view>
  <view wx:if="{{todosOfComplted.length > 0}}">
   <button type="warn" size="mini" bindtap="clearAll" loading="{{clearAllLoading}}" disabled="{{clearAllLoading}}"> 
    Clear {{todosOfComplted.length}} of done.
   </button>
  </view>
 </view>
 <loading hidden="{{loadingHidden}}" bindchange="loadingChange">
  {{loadingText}}
 </loading>
 <toast hidden="{{toastHidden}}" bindchange="toastChange">
  {{toastText}}
 </toast>
</view>

index.js的源码:

var app = getApp();

Page( {
 data: {
  todos: [],
  todosOfUncomplted: [],
  todosOfComplted: [],
  newTodoText: &#39;&#39;,
  addOneLoading: false,
  loadingHidden: true,
  loadingText: &#39;&#39;,
  toastHidden: true,
  toastText: &#39;&#39;,
  clearAllLoading: false
 },
 updateData: function( resetTodos ) {
  var data = {};
  if( resetTodos ) {
   data.todos = this.data.todos;
  }

  data.todosOfUncomplted = this.data.todos.filter( function( t ) {
   return !t.complete;
  });

  data.todosOfComplted = this.data.todos.filter( function( t ) {
   return t.complete;
  });

  this.setData( data );
 },
 updateStorage: function() {
  var storage = [];
  this.data.todos.forEach( function( t ) {
   storage.push( {
    id: t.id,
    text: t.text,
    complete: t.complete
   })
  });

  wx.setStorageSync( &#39;todos&#39;, storage );
 },
 onLoad: function() {
  this.setData( {
   todos: wx.getStorageSync( &#39;todos&#39; ) || []
  });
  this.updateData( false );
 },
 getTodo: function( id ) {
  return this.data.todos.filter( function( t ) {
   return id == t.id;
  })[ 0 ];
 },
 getTodoId: function( e, prefix ) {
  return e.currentTarget.id.substring( prefix.length );
 },
 toggleTodo: function( e ) {

  var id = this.getTodoId( e, &#39;todo-item-chk-&#39; );
  var value = e.detail.value[ 0 ];
  var complete = !!value;
  var todo = this.getTodo( id );

  todo.complete = complete;
  this.updateData( true );
  this.updateStorage();
 },
 toggleAll: function( e ) {
  var value = e.detail.value[ 0 ];
  var complete = !!value;

  this.data.todos.forEach( function( t ) {
   t.complete = complete;
  });

  this.updateData( true );
  this.updateStorage();

 },
 clearTodo: function( id ) {
  var targetIndex;
  this.data.todos.forEach( function( t, i ) {
   if( targetIndex !== undefined ) return;

   if( t.id == id ) {
    targetIndex = i;
   }
  });

  this.data.todos.splice( targetIndex, 1 );
 },
 clearSingle: function( e ) {
  var id = this.getTodoId( e, &#39;btn-del-item-&#39; );
  var todo = this.getTodo( id );

  todo.loading = true;
  this.updateData( true );

  var that = this;
  setTimeout( function() {
   that.clearTodo( id );
   that.updateData( true );
   that.updateStorage();
  }, 500 );
 },
 clearAll: function() {
  this.setData( {
   clearAllLoading: true
  });

  var that = this;
  setTimeout( function() {
   that.data.todosOfComplted.forEach( function( t ) {
    that.clearTodo( t.id );
   });
   that.setData( {
    clearAllLoading: false
   });
   that.updateData( true );
   that.updateStorage();

   that.setData( {
    toastHidden: false,
    toastText: &#39;Success&#39;
   });
  }, 500 );

 },
 startEdit: function( e ) {
  var id = this.getTodoId( e, &#39;todo-item-txt-&#39; );
  var todo = this.getTodo( id );
  todo.editing = true;

  this.updateData( true );
  this.updateStorage();
 },
 newTodoTextInput: function( e ) {
  this.setData( {
   newTodoText: e.detail.value
  });
 },
 endEditTodo: function( e ) {
  var id = this.getTodoId( e, &#39;todo-item-edit-&#39; );
  var todo = this.getTodo( id );

  todo.editing = false;
  todo.text = e.detail.value;

  this.updateData( true );
  this.updateStorage();
 },
 addOne: function( e ) {
  if( !this.data.newTodoText ) return;

  this.setData( {
   addOneLoading: true
  });

  //open loading
  this.setData( {
   loadingHidden: false,
   loadingText: &#39;Waiting...&#39;
  });

  var that = this;
  setTimeout( function() {
   //close loading and toggle button loading status
   that.setData( {
    loadingHidden: true,
    addOneLoading: false,
    loadingText: &#39;&#39;
   });

   that.data.todos.push( {
    id: app.getId(),
    text: that.data.newTodoText,
    compelte: false
   });

   that.setData( {
    newTodoText: &#39;&#39;
   });

   that.updateData( true );
   that.updateStorage();
  }, 500 );
 },
 loadingChange: function() {
  this.setData( {
   loadingHidden: true,
   loadingText: &#39;&#39;
  });
 },
 toastChange: function() {
  this.setData( {
   toastHidden: true,
   toastText: &#39;&#39;
  });
 }
});

最后需要补充的是,这个app在有限的时间内依据微信的官方文档进行开发,所以这里面的实现方式到底是不是合理的,我也不清楚。我也仅仅是通过这个app来了解小程序这个平台的用法。希望微信官方能够推出一些更全面、最好是项目性的demo,在代码层面,给我们这些开发者提供一个最佳实践规范。欢迎有其它的开发思路的朋友,帮我指出我以上实现中的问题。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

关于微信小程序解析网页内容的介绍

关于微信小程序的动态传参

关于微信JS-SDK选取手机照片上传的功能

위 내용은 WeChat 미니 프로그램의 프레임워크 분석의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.