使用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統一多端開發之頁面跳轉和發送請求(附源碼)


分享到:


相關文章: