使用Taro统一多端开发之页面跳转和发送请求

版权声明: https://blog.csdn.net/qq1311256696/article/details/87896090

这节中我们使用taro-cli为我们生成的项目添加功能。

1.png

新建页面

在page下新建test1文件夹,先把index下的模板文件复制过去。
QQ图片20190222190135.png

声明页面

  • 修改app.js,在config中的page下新增test1页面路径:
pages: [
      'pages/index/index',
      'pages/test1/index',
    ],
  • 在config下新增tabBar节点:
tabBar: {
      list: [
        {
          pagePath: "pages/index/index",
          text: "首页",
          iconPath: "./images/tab/home.png",
          selectedIconPath: "./images/tab/home-active.png"
        },
        {
          pagePath: "pages/test1/index",
          text: "测试1",
          iconPath: "./images/tab/home.png",
          selectedIconPath: "./images/tab/home-active.png"
        }]
    }

其中的图片需要放在相应的路径下。

修改test1页面

  • 在test1页面的index.js中加入构造方法:
constructor(props) {
    super(props);
  };
  • 修改页面模板:
render () {
    return (
      <View className='test1'>
        <Text>Hello test1!</Text>
        <Button onClick={this.request}>点我发请求</Button>
      </View>
    )
  }

由于用到了Button元素,因此在页面最顶层引入button

import { View, Text, Button } from '@tarojs/components'
  • 按钮上加入了点击事件,因此加入方法。
// 发送请求
  request(){
    const params = {
      url: "https://www.baidu.com/",
      data: {},
      method: "POST",
      success: (data) => {console.log(data)},
      fail: (data) => {console.log(data)}
    };
    Taro.request(params)
  }

修改index页面

  • 修改页面模板:
render () {
    return (
      <View className='index'>
        <Text>Hello world!</Text>
        <Button onClick={this.toPage}>跳转页面</Button>
      </View>
    )
  }
  • 按钮上加入了点击事件,因此加入方法。
 // 跳转页面
   toPage() {
    if (Taro.getEnv() == Taro.ENV_TYPE.WEB) {
      Taro.navigateTo({
        url: '/pages/test1/index',
      })
    } else {
      Taro.switchTab({
        url: '/pages/test1/index',
      })
    }
  }

运行

npm run dev:h5

点击跳转页面可以跳到第二个页面,在第二个页面点击发送请求可以在network中看到相应请求。

猜你喜欢

转载自blog.csdn.net/qq1311256696/article/details/87896090