uni、uview自定义步进器、购物车加减
在uni-app中使用uView UI框架创建自定义步进器,并集成到购物车中,可以通过以下步骤实现:
- 安装uView UI:在项目根目录打开终端,运行以下命令安装uView UI。
npm install uview-ui
- 在
main.js
中引入uView UI:
import Vue from 'vue'
import App from './App'
import uView from 'uview-ui'
Vue.use(uView)
const app = new Vue({
...App
})
app.$mount()
- 创建自定义步进器组件
stepper.vue
:
<template>
<view class="u-step">
<u-button @click="sub" :disabled="num <= 1">-</u-button>
<input class="u-input" type="number" v-model="num" @input="handleInput" />
<u-button @click="add">+</u-button>
</view>
</template>
<script>
export default {
props: {
value: {
type: Number,
default: 1
},
stock: {
type: Number,
default: 999
}
},
data() {
return {
num: this.value
}
},
methods: {
sub() {
if (this.num > 1) {
this.num -= 1;
this.$emit('input', this.num);
}
},
add() {
if (this.num < this.stock) {
this.num += 1;
this.$emit('input', this.num);
}
},
handleInput(e) {
let value = e.target.value;
value = value.replace(/\D/g, '') || '1';
value = Number(value);
if (value > this.stock) {
value = this.stock;
} else if (value < 1) {
value = 1;
}
this.num = value;
this.$emit('input', this.num);
}
},
watch: {
value(newVal) {
this.num = newVal;
}
}
}
</script>
<style scoped>
.u-step {
display: flex;
align-items: center;
}
.u-input {
width: 40px;
text-align: center;
margin: 0 10px;
}
</style>
- 使用自定义步进器组件
stepper.vue
:
<template>
<view>
<stepper v-model="cartNum" :stock="stock"></stepper>
</view>
</template>
<script>
import Stepper from './stepper.vue'
export default {
components: {
Stepper
},
data() {
return {
cartNum: 1,
stock: 999
}
}
}
</script>
在上述代码中,我们
评论已关闭