選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 

405 行
13 KiB

  1. <template>
  2. <view
  3. class="u-rate"
  4. :id="elId"
  5. ref="u-rate"
  6. :style="[addStyle(customStyle)]"
  7. >
  8. <view
  9. class="u-rate__content"
  10. @touchmove.stop="touchMove"
  11. @touchend.stop="touchEnd"
  12. >
  13. <view
  14. class="u-rate__content__item cursor-pointer"
  15. v-for="(item, index) in Number(count)"
  16. :key="index"
  17. :class="[elClass]"
  18. >
  19. <view
  20. class="u-rate__content__item__icon-wrap"
  21. ref="u-rate__content__item__icon-wrap"
  22. @tap.stop="clickHandler($event, index + 1)"
  23. >
  24. <up-icon
  25. :name="
  26. Math.floor(activeIndex) > index
  27. ? activeIcon
  28. : inactiveIcon
  29. "
  30. :color="
  31. disabled
  32. ? disabledColorInner
  33. : Math.floor(activeIndex) > index
  34. ? activeColorInner
  35. : inactiveColorInner
  36. "
  37. :custom-style="{
  38. padding: `0 ${addUnit(gutter / 2)}`,
  39. }"
  40. :size="size"
  41. ></up-icon>
  42. </view>
  43. <view
  44. v-if="allowHalf"
  45. @tap.stop="clickHandler($event, index + 1)"
  46. class="u-rate__content__item__icon-wrap u-rate__content__item__icon-wrap--half"
  47. :style="[{
  48. width: addUnit(rateWidth / 2),
  49. }]"
  50. ref="u-rate__content__item__icon-wrap"
  51. >
  52. <up-icon
  53. :name="
  54. Math.ceil(activeIndex) > index
  55. ? activeIcon
  56. : inactiveIcon
  57. "
  58. :color="
  59. disabled
  60. ? disabledColorInner
  61. : Math.ceil(activeIndex) > index
  62. ? activeColorInner
  63. : inactiveColorInner
  64. "
  65. :custom-style="{
  66. padding: `0 ${addUnit(gutter / 2)}`
  67. }"
  68. :size="size"
  69. ></up-icon>
  70. </view>
  71. </view>
  72. </view>
  73. </view>
  74. </template>
  75. <script>
  76. import { props } from './props';
  77. import { mpMixin } from '../../libs/mixin/mpMixin';
  78. import { mixin } from '../../libs/mixin/mixin';
  79. import { addUnit, addStyle, guid, sleep, range, os } from '../../libs/function/index';
  80. // #ifdef APP-NVUE
  81. const dom = weex.requireModule("dom");
  82. // #endif
  83. /**
  84. * rate 评分
  85. * @description 该组件一般用于满意度调查,星型评分的场景
  86. * @tutorial https://uview-plus.jiangruyi.com/components/rate.html
  87. * @property {String | Number} value 用于v-model双向绑定选中的星星数量 (默认 1 )
  88. * @property {String | Number} count 最多可选的星星数量 (默认 5 )
  89. * @property {Boolean} disabled 是否禁止用户操作 (默认 false )
  90. * @property {Boolean} readonly 是否只读 (默认 false )
  91. * @property {String | Number} size 星星的大小,单位px (默认 18 )
  92. * @property {String} inactiveColor 未选中星星的颜色 (默认 '#b2b2b2' )
  93. * @property {String} activeColor 选中的星星颜色 (默认 '#FA3534' )
  94. * @property {String | Number} gutter 星星之间的距离 (默认 4 )
  95. * @property {String | Number} minCount 最少选中星星的个数 (默认 1 )
  96. * @property {Boolean} allowHalf 是否允许半星选择 (默认 false )
  97. * @property {String} activeIcon 选中时的图标名,只能为uView的内置图标 (默认 'star-fill' )
  98. * @property {String} inactiveIcon 未选中时的图标名,只能为uView的内置图标 (默认 'star' )
  99. * @property {Boolean} touchable 是否可以通过滑动手势选择评分 (默认 'true' )
  100. * @property {Object} customStyle 组件的样式,对象形式
  101. * @event {Function} change 选中的星星发生变化时触发
  102. * @example <u-rate :count="count" :value="2"></u-rate>
  103. */
  104. export default {
  105. name: "u-rate",
  106. mixins: [mpMixin, mixin, props],
  107. data() {
  108. const modelVal = Number(this.modelValue)
  109. const valueVal = Number(this.value)
  110. const minCount = Number(this.minCount)
  111. const defaultActive = Number.isFinite(minCount) ? minCount : 0
  112. return {
  113. // 生成一个唯一id,否则一个页面多个评分组件,会造成冲突
  114. elId: guid(),
  115. elClass: guid(),
  116. rateBoxLeft: 0, // 评分盒子左边到屏幕左边的距离,用于滑动选择时计算距离
  117. // #ifdef VUE3
  118. activeIndex: Number.isFinite(modelVal) ? modelVal : defaultActive,
  119. // #endif
  120. // #ifdef VUE2
  121. activeIndex: Number.isFinite(valueVal) ? valueVal : defaultActive,
  122. // #endif
  123. rateWidth: 0, // 每个星星的宽度
  124. // 标识是否正在滑动,由于iOS事件上touch比click先触发,导致快速滑动结束后,接着触发click,导致事件混乱而出错
  125. moving: false,
  126. };
  127. },
  128. watch: {
  129. // #ifdef VUE3
  130. modelValue(val) {
  131. this.activeIndex = this.normalizeActiveIndex(val);
  132. },
  133. // #endif
  134. // #ifdef VUE2
  135. value(val) {
  136. this.activeIndex = this.normalizeActiveIndex(val);
  137. },
  138. // #endif
  139. activeIndex: 'emitEvent'
  140. },
  141. computed: {
  142. disabledColorInner() {
  143. return this.upThemeVar('--up-disabled-color', '#c8c9cc')
  144. },
  145. activeColorInner() {
  146. return this.activeColor || this.upThemeVar('--up-primary', '#FA3534')
  147. },
  148. inactiveColorInner() {
  149. return this.inactiveColor || this.upThemeVar('--up-tips-color', '#b2b2b2')
  150. }
  151. },
  152. // #ifdef VUE3
  153. emits: ['update:modelValue', 'change'],
  154. // #endif
  155. methods: {
  156. addStyle,
  157. addUnit,
  158. toNumber(value, fallback = 0) {
  159. const num = Number(value)
  160. return Number.isFinite(num) ? num : fallback
  161. },
  162. getMinCountValue() {
  163. return this.toNumber(this.minCount, 0)
  164. },
  165. getCountValue() {
  166. return this.toNumber(this.count, 0)
  167. },
  168. normalizeActiveIndex(value) {
  169. let normalized = this.toNumber(value, this.getMinCountValue())
  170. const minCount = this.getMinCountValue()
  171. const count = this.getCountValue()
  172. if (normalized < minCount) normalized = minCount
  173. if (count > 0 && normalized > count) normalized = count
  174. return normalized
  175. },
  176. getFallbackRateWidth() {
  177. const size = parseFloat(this.size) || 18
  178. const gutter = parseFloat(this.gutter) || 0
  179. const width = size + gutter
  180. return width > 0 ? width : 18
  181. },
  182. ensureRateMetrics() {
  183. if (!Number.isFinite(this.rateBoxLeft)) {
  184. this.rateBoxLeft = 0
  185. }
  186. if (!Number.isFinite(this.rateWidth) || this.rateWidth <= 0) {
  187. this.rateWidth = this.getFallbackRateWidth()
  188. this.getRateIconWrapRect()
  189. }
  190. return Number.isFinite(this.rateWidth) && this.rateWidth > 0
  191. },
  192. init() {
  193. sleep().then(() => {
  194. this.getRateItemRect();
  195. this.getRateIconWrapRect();
  196. })
  197. },
  198. // 获取评分组件盒子的布局信息
  199. async getRateItemRect() {
  200. await sleep();
  201. // uView封装的获取节点的方法,详见文档
  202. // #ifndef APP-NVUE
  203. this.$uGetRect("#" + this.elId).then((res) => {
  204. if (res && Number.isFinite(res.left)) {
  205. this.rateBoxLeft = res.left;
  206. }
  207. });
  208. // #endif
  209. // #ifdef APP-NVUE
  210. dom.getComponentRect(this.$refs["u-rate"], (res) => {
  211. const left = res && res.size ? res.size.left : NaN
  212. if (Number.isFinite(left)) {
  213. this.rateBoxLeft = left;
  214. }
  215. });
  216. // #endif
  217. },
  218. // 获取单个星星的尺寸
  219. getRateIconWrapRect() {
  220. // uView封装的获取节点的方法,详见文档
  221. // #ifndef APP-NVUE
  222. this.$uGetRect("." + this.elClass).then((res) => {
  223. if (res && Number.isFinite(res.width) && res.width > 0) {
  224. this.rateWidth = res.width;
  225. }
  226. });
  227. // #endif
  228. // #ifdef APP-NVUE
  229. dom.getComponentRect(
  230. this.$refs["u-rate__content__item__icon-wrap"][0],
  231. (res) => {
  232. const width = res && res.size ? res.size.width : NaN
  233. if (Number.isFinite(width) && width > 0) {
  234. this.rateWidth = width;
  235. }
  236. }
  237. );
  238. // #endif
  239. },
  240. // 手指滑动
  241. touchMove(e) {
  242. // 如果禁止通过手动滑动选择,返回
  243. if (!this.touchable) {
  244. return;
  245. }
  246. this.preventEvent(e);
  247. this.ensureRateMetrics();
  248. const x = e.changedTouches[0].pageX;
  249. this.getActiveIndex(x);
  250. },
  251. // 停止滑动
  252. touchEnd(e) {
  253. // 如果禁止通过手动滑动选择,返回
  254. if (!this.touchable) {
  255. return;
  256. }
  257. this.preventEvent(e);
  258. this.ensureRateMetrics();
  259. const x = e.changedTouches[0].pageX;
  260. this.getActiveIndex(x);
  261. },
  262. // 通过点击,直接选中
  263. clickHandler(e, index) {
  264. // ios上,moving状态取消事件触发
  265. if (os() === "ios" && this.moving) {
  266. return;
  267. }
  268. this.preventEvent(e);
  269. this.ensureRateMetrics();
  270. let x = 0;
  271. // 点击时,在nvue上,无法获得点击的坐标,所以无法实现点击半星选择
  272. // #ifndef APP-NVUE
  273. x = e.changedTouches[0].pageX;
  274. // #endif
  275. // #ifdef APP-NVUE
  276. // nvue下,无法通过点击获得坐标信息,这里通过元素的位置尺寸值模拟坐标
  277. x = index * this.rateWidth + this.rateBoxLeft;
  278. // #endif
  279. this.getActiveIndex(x,true);
  280. },
  281. // 发出事件
  282. emitEvent() {
  283. const normalizedValue = this.normalizeActiveIndex(this.activeIndex)
  284. if (!Number.isFinite(this.activeIndex) || normalizedValue !== this.activeIndex) {
  285. this.activeIndex = normalizedValue
  286. return
  287. }
  288. // 发出change事件
  289. this.$emit("change", normalizedValue);
  290. // 同时修改双向绑定的值
  291. // #ifdef VUE3
  292. this.$emit("update:modelValue", normalizedValue);
  293. // #endif
  294. // #ifdef VUE2
  295. this.$emit("input", normalizedValue);
  296. // #endif
  297. },
  298. // 获取当前激活的评分图标
  299. getActiveIndex(x,isClick = false) {
  300. if (this.disabled || this.readonly) {
  301. return;
  302. }
  303. if (!this.ensureRateMetrics()) {
  304. return;
  305. }
  306. const count = this.getCountValue()
  307. if (count <= 0) {
  308. return;
  309. }
  310. if (!Number.isFinite(x)) {
  311. return;
  312. }
  313. // 判断当前操作的点的x坐标值,是否在允许的边界范围内
  314. const allRateWidth = this.rateWidth * count + this.rateBoxLeft;
  315. // 如果小于第一个图标的左边界,设置为最小值,如果大于所有图标的宽度,则设置为最大值
  316. x = range(this.rateBoxLeft, allRateWidth, x) - this.rateBoxLeft
  317. // 滑动点相对于评分盒子左边的距离
  318. const distance = x;
  319. // 滑动的距离,相当于多少颗星星
  320. let index;
  321. // 判断是否允许半星
  322. if (this.allowHalf) {
  323. index = Math.floor(distance / this.rateWidth);
  324. // 取余,判断小数的区间范围
  325. const decimal = distance % this.rateWidth;
  326. if (decimal <= this.rateWidth / 2 && decimal > 0) {
  327. index += 0.5;
  328. } else if (decimal > this.rateWidth / 2) {
  329. index++;
  330. }
  331. } else {
  332. index = Math.floor(distance / this.rateWidth);
  333. // 取余,判断小数的区间范围
  334. const decimal = distance % this.rateWidth;
  335. // 非半星时,只有超过了图标的一半距离,才认为是选择了这颗星
  336. if (isClick){
  337. if (decimal > 0) index++;
  338. } else {
  339. if (decimal > this.rateWidth / 2) index++;
  340. }
  341. }
  342. this.activeIndex = this.normalizeActiveIndex(Math.min(index, count));
  343. // 对最少颗星星的限制
  344. if (this.activeIndex < this.getMinCountValue()) {
  345. this.activeIndex = this.getMinCountValue();
  346. }
  347. // 设置延时为了让click事件在touchmove之前触发
  348. setTimeout(() => {
  349. this.moving = true;
  350. }, 10);
  351. // 一定时间后,取消标识为移动中状态,是为了让click事件无效
  352. setTimeout(() => {
  353. this.moving = false;
  354. }, 10);
  355. },
  356. },
  357. mounted() {
  358. this.init();
  359. },
  360. };
  361. </script>
  362. <style lang="scss" scoped>
  363. $u-rate-margin: 0 !default;
  364. $u-rate-padding: 0 !default;
  365. $u-rate-item-icon-wrap-half-top: 0 !default;
  366. $u-rate-item-icon-wrap-half-left: 0 !default;
  367. .u-rate {
  368. @include flex;
  369. align-items: center;
  370. margin: $u-rate-margin;
  371. padding: $u-rate-padding;
  372. /* #ifndef APP-NVUE */
  373. touch-action: none;
  374. /* #endif */
  375. &__content {
  376. @include flex;
  377. &__item {
  378. position: relative;
  379. &__icon-wrap {
  380. &--half {
  381. position: absolute;
  382. overflow: hidden;
  383. top: $u-rate-item-icon-wrap-half-top;
  384. left: $u-rate-item-icon-wrap-half-left;
  385. }
  386. }
  387. }
  388. }
  389. }
  390. .up-icon {
  391. /* #ifndef APP-NVUE */
  392. box-sizing: border-box;
  393. /* #endif */
  394. }
  395. </style>