Taro Vue3 Nutui开发小程序中的4个点

378 阅读4分钟

前言

此文是对上一篇文章的延续,我会把我搭建项目初期以及过程中的一些思考以文章的形式进行记录,如果你对微信小程序原生写法有过了解,那么使用Taro进行开发也会得心应手,因为Taro就是基于微信小程序作为标准,一统多端小程序的。
看标题可知,我在规划此文的时候按照排版布局路由跳转网络请求状态管理4个部分展开,我想你在搭建项目初期也会最关注这几个方向。

排版布局

在我们不熟悉框架的时候第一时间先看看官网怎么说:

View 组件。这是来源于 @tarojs/components 的跨平台组件。相对于我们熟悉的 divspan 元素而言,在 Taro 中我们要全部使用这样的跨平台组件进行开发。

so,我们要通过view作为容器来进行我们的排版,在画页面之前,你要明确好这一点,很重要

在 Taro 中尺寸单位建议使用 px、 百分比 %,Taro 默认会对所有单位进行转换。在 Taro 中书写尺寸按照 1:1 的关系来进行书写,即从设计稿上量的长度 100px,那么尺寸书写就是 100px,当转成微信小程序的时候,尺寸将默认转换为 100rpx,当转成 H5 时将默认转换为以 rem 为单位的值。

那让我们趁热打铁,再画一个详情页为路由跳转作准备吧:

<template>
  <view class="detail">
    <nut-swiper
      :init-page="state.page"
      :pagination-visible="true"
      pagination-color="#426543"
      auto-play="3000"
    >
      <nut-swiper-item v-for="(item, index) in state.list" :key="index">
        <img :src="item" alt="" />
      </nut-swiper-item>
    </nut-swiper>

    <nut-row>
      <nut-col :span="24">
        <view class="good-title">XXX商品详情</view>
        <view class="good-info">
          商品介绍商品介绍商品介绍商品介绍商品介绍商品介绍
        </view>
        <view>
          <nut-price :price="8888" :decimal-digits="0" />
        </view>
        <view>
          <nut-button type="primary">加入购物车</nut-button>
        </view>
      </nut-col>
    </nut-row>

    <nut-comment
      headerType="complex"
      imagesRows="multi"
      :images="state.comment"
      ellipsis="6"
    >
      <template #comment-shop-reply>
        <view class="nut-comment-shop">
          <view style="display: inline-block">京东美妆国际:</view
          >尊敬的客户您好,非常抱歉给您带来不愉快的购物体验,关于过敏,什么成分都不存在个别性和普遍性。
        </view>
      </template>
    </nut-comment>
  </view>
</template>

<script setup>
import { onMounted, reactive } from 'vue';

const state = reactive({
  page: 2,
  list: [],
  comment: [],
});
const comment = reactive([]);
onMounted(() => {
  state.list = [
    'https://storage.360buyimg.com/jdc-article/NutUItaro34.jpg',
    'https://storage.360buyimg.com/jdc-article/NutUItaro2.jpg',
    'https://storage.360buyimg.com/jdc-article/welcomenutui.jpg',
    'https://storage.360buyimg.com/jdc-article/fristfabu.jpg',
  ];

  state.comment = [
    {
      smallImgUrl: '',
      bigImgUrl: '',
      imgUrl:
        'https://img30.360buyimg.com/imagetools/jfs/t1/153847/3/5051/62777/5fa65e01Ec88cecb9/36ba206949050b39.jpg',
    },
    {
      smallImgUrl: '',
      bigImgUrl: '',
      imgUrl:
        'https://img30.360buyimg.com/imagetools/jfs/t1/153847/3/5051/62777/5fa65e01Ec88cecb9/36ba206949050b39.jpg',
    },
    {
      smallImgUrl: '',
      bigImgUrl: '',
      imgUrl:
        'https://img30.360buyimg.com/imagetools/jfs/t1/153847/3/5051/62777/5fa65e01Ec88cecb9/36ba206949050b39.jpg',
    },
  ];
});
</script>

<style lang="less">
.detail {
  padding: 15px;
}
.nut-swiper-item {
  line-height: 300px;
  img {
    width: 100%;
    height: 100%;
  }
}
.good-title {
  margin-top: 15px;
  font-size: 28px;
}
.good-info {
  font-size: 24px;
  color: #666;
}
</style>

看下效果吧:

image.png

路由跳转

首先明确一下目前page目录的结构:

image.png
好了,让我们实现从列表页跳转到详情页吧:
step1:先在app.config.ts页面在pages处新增我们的detail的路由

export default defineAppConfig({
  pages: ['pages/index/index', 'pages/detail/index'],
  window: {
    backgroundTextStyle: 'light',
    navigationBarBackgroundColor: '#fff',
    navigationBarTitleText: 'WeChat',
    navigationBarTextStyle: 'black',
  },
});

step2:在我们之前开发的列表页新增跳转方法绑定点击事件

image.png

const clickJump = () => {
  Taro.navigateTo({
    url: 'pages/detail/index',
  });
};

好啦,页面的跳转就完成啦,当然真实开发中肯定要去请求后端接口。

网络请求

先看一下官网的demo:

Taro.request({  
    url: 'test.php', //仅为示例,并非真实的接口地址  
    data: {  
        x: '',  
        y: ''  
    },  
    header: {  
        'content-type': 'application/json' // 默认值  
    },  
    success: function (res) {  
        console.log(res.data)  
    }  
})

我们要对其进行封装,方便我们在项目里方便调用:

// request.js
import Taro from '@tarojs/taro';
// 这里是获取环境变量中定义的url
const BASE_URL = process.env.APP_API;
export const request = (url,method='GET',params={}) => {
    // 从本地缓存中获取token,用于下方存入header中
    const token = Taro.getStorageSync('token');
    return new Promise((resolve,reject)=>{
        Taro.request({
          url: BASE_URL + url,
          method: method,
          data: params,
          header: {
            'content-type': 'application/json;charset=utf-8',
            Authorization: token
          },
          mode: 'cors', // 允许跨域请求
          success({ data }) {
            resolve(data);
          },
          fail(err) {
            reject(err);
          },
        });
    })
}

状态管理

这里我们选用pinia,开始封装store/login.js:

import Taro from '@tarojs/taro';
import { defineStore } from 'pinia';
// 引入请求后端登录的接口方法 这里这里写伪代码 import {login} from '...'
export const useLoginStore = defineStore('userLogin', {
  state: () => {
      return { 
          token: Taro.getStorageSync('token') || null,
          userLogin: Taro.getStorageSync('userLogin') || null,
      }
  },
  getters: {},
  actions: {
    increment() {
      this.count++
    },
    // login
    myLogin(){
        return new Promise((resolve,reject)=>{
            const {data} = await login(params)
            const token = data.token
            // 设置token
            Taro.setStorageSync('token', token);
        })
    }
  },
})

登录页面调用:

import { useLoginStore } from '@/store/login.js';
const piniaStore = useLoginStore()
const loginHandle = async()=>{
    await piniaStore.myLogin(这里填入登录页面获取的参数)
}
//在登录的位置绑定点击回调事件即可

尾声

写到这里,或许你已经对Taro来开发小程序有了一个大概的认识,其实对比直接用vue来写项目,也差不多,只不过以前用axios请求要换成Taro封装的请求,包括一些状态管理的概念也是可以复用之前的一些逻辑,而且Taro还贴心的帮你做了移动端适配,你需要了解你的设计稿尺寸去做对应的调整。当然了,我这里写了很多伪代码,希望你能够有一个整体的认识,具体的细节由自己来亲自完善,你需要去详细的了解Taro以及微信小程序的文档,在开发中如果遇到可以改进优化的地方我会再回来完善,也欢迎你一起加入Taro开发小程序的道路。