1. 首先安裝 Taro.js 和 NutUI:
```
npm install -g @tarojs/cli
npm install taro-ui
```
2. 創(chuàng)建 Taro 項目并進入項目目錄:
```
taro init myapp
cd myapp
```
3. 選用 Taro 模板一并安裝依賴:
```
npm install
```
4. 在頁面目錄中創(chuàng)建商品選擇頁:
```
taro create --name goods --type page
```
5. 在 `goods.jsx`中導(dǎo)入并使用 Taro-ui 組件庫相關(guān)的組件:
```jsx
import Taro, { useState } from "@tarojs/taro";
import { View, Text, Image, Button, Checkbox, CheckboxGroup } from "@tarojs/components";
import { AtInputNumber, AtDivider, AtButton } from "taro-ui";
// 這里假設(shè)我們有兩個規(guī)格參數(shù),分別是顏色和尺碼,定義一個數(shù)組
const skuList = [
{
id: 1,
spec: ['紅色', 'L'],
price: 100,
},
{
id: 2,
spec: ['紅色', 'M'],
price: 98,
},
{
id: 3,
spec: ['藍色', 'L'],
price: 99,
},
{
id: 4,
spec: ['藍色', 'M'],
price: 97,
},
];
export default function Goods() {
// 存儲當(dāng)前選擇的規(guī)格,初始為空
const [spec, setSpec] = useState([]);
// 存儲當(dāng)前選擇的數(shù)量,初始為1
const [num, setNum] = useState(1);
return (
<View>
{/* 商品信息 */}
<View>
<Image src="https://placehold.it/100" />
<Text>商品名稱</Text>
<Text>商品價格</Text>
</View>
<AtDivider />
{/* 規(guī)格選擇 */}
<View>
<Text>選擇: {spec.join('-')}</Text>
<View>選擇顏色</View>
<CheckboxGroup onChange={value => setSpec(value)}>
{
[...new Set(skuList.map(i => i.spec[0]))].map((color, index) =>
<Checkbox key={index} value={color}>{color}</Checkbox>)
}
</CheckboxGroup>
<View>選擇尺碼</View>
<CheckboxGroup onChange={value => setSpec(prev => ([...prev, ...value]))}>
{
[...new Set(skuList.map(i => i.spec[1]))].map((size, index) => (
<Checkbox key={index} value={size}>{size}</Checkbox>
))
}
</CheckboxGroup>
<AtDivider />
{/* 購買數(shù)量 */}
<View>
<AtInputNumber
min={1}
max={100}
step={1}
value={num}
onChange={value => setNum(value)}
/>
</View>
<AtDivider />
{/* 確認按鈕 */}
<View>
<AtButton type='primary'>確認</AtButton>
</View>
</View>
</View>
);
}
```
6. 在 `app.jsx` 中注冊并配置 Taro-ui 組件庫:
```jsx
import Taro from "@tarojs/taro";
import { AtButton } from "taro-ui";
import "taro-ui/dist/style/index.scss"; // 一定要引入樣式
function App({ children }) {
return <View>{children}</View>;
}
export default App;
```
這樣,在 Taro.js 和 NutUI 的基礎(chǔ)上我們已經(jīng)編寫了一個基本的商品選擇頁面。當(dāng)用戶選擇商品規(guī)格和數(shù)量后,點擊確認按鈕即可觸發(fā)相應(yīng)的事件進行下單操作。
需要注意的是,這里使用了不少的 Taro-ui 組件,比如 `AtInputNumber`、`AtDivider` 以及 `AtButton` 等等。需要在代碼中導(dǎo)入這些組件并聲明相關(guān)使用,文章來源:http://www.zghlxwxcb.cn/news/detail-679581.html
若有收獲,就點個贊吧文章來源地址http://www.zghlxwxcb.cn/news/detail-679581.html
到了這里,關(guān)于taro.js和nutui實現(xiàn)商品選擇頁面的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!