美文网首页前端Vue专辑Vue.js
使用Taro统一多端开发之页面跳转和发送请求

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

作者: 我的小熊不见了 | 来源:发表于2019-02-22 19:20 被阅读10次

    这节中我们使用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中看到相应请求。

    相关文章

      网友评论

        本文标题:使用Taro统一多端开发之页面跳转和发送请求

        本文链接:https://www.haomeiwen.com/subject/boqyyqtx.html