使用Taro统一多端开发之页面跳转和发送请求(附源码)

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


使用Taro统一多端开发之页面跳转和发送请求(附源码)


1.png

新建页面

在page下新建test1文件夹,先把index下的模板文件复制过去。


使用Taro统一多端开发之页面跳转和发送请求(附源码)


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"
}]
}

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

使用Taro统一多端开发之页面跳转和发送请求(附源码)

修改test1页面

  • 在test1页面的index.js中加入构造方法:
constructor(props) {
super(props);
};
  • 修改页面模板:
render () {
return (
<view>
<text>Hello test1!/<text>
<button>点我发请求/<button>
/<view>
)
}

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

使用Taro统一多端开发之页面跳转和发送请求(附源码)

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>
<text>Hello world!/<text>
<button>跳转页面/<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统一多端开发之页面跳转和发送请求(附源码)


分享到:


相關文章: