애플릿의 wxml에 함수 로직을 작성하는 방법, wxs 사용

애플릿 wxml의 페이지에서 { {}}를 사용하여 삼항 연산자 등과 같은 간단한 js 표현식을 작성할 수 있지만 약간 더 복잡한 논리의 경우 이를 해결하기 위해 함수를 사용해야 합니다. 그 중 일부는 번거롭고 데이터를 바인딩해야 하는 등 이 때 wxs를 사용할 수 있도록 장착되어 있습니다.  wxs는 ES5만 지원합니다! ! !

1. 사례 설명:

아래 그림에서 가격 부분의 논리를 구현하겠습니다.프론트 엔드에서 반환되는 현상에는 price와 discount_price 두 가지 속성이 있습니다.할인 가격이 null이면 원래 가격 만 표시됩니다.할인 가격이 비어 있지 않으면 할인 가격이 표시되고 원래 가격이 그려집니다.

별도의 파일에 작성:

1. 접미사가 wxs인 파일을 만들고 함수 논리를 작성합니다.

// 如果不进行函数处理,当只有一个原价时,它会将原价也打上删除线,所以必须用该逻辑实现

// 最终要显示的价格
function showPrice(price, discountPrice) {
    if (!discountPrice) {
        return {
            price: price,
            display: true
        }
    } else {
        return {
            price: discountPrice,
            display: true
        }
    }
}

// 显示有切割线的那个价格
function cutPrice(price, discountPrice) {
    if (discountPrice) {
        return {
            price: price,
            display: true
        }
    } else {
        return {
            price: '',
            display: false
        }
    }
}
// 导出这两个函数
module.exports = {
    showPrice: showPrice,
    cutPrice: cutPrice
}

2. wxml에 삽입합니다.

모듈은 나중에 동작할 객체와 동일합니다.

<!-- 导入wxs逻辑 -->
<wxs src="../../wxs/price.wxs" module="p"></wxs>

3. 해당 라벨에 사용:

<l-price 
    value="{
   
   {p.showPrice(data.price,data.discount_price).price}}">
</l-price>
<l-price  
    wx:if="{
   
   {p.cutPrice(data.price,data.discount_price).display}}" 
    deleted 
    value="{
   
   {p.cutPrice(data.price,data.discount_price).price}}">
</l-price>

wxml에서 직접 작성:

html과 유사한 <script>는 다음과 같이 작성됩니다.

<l-price 
    value="{
   
   {p.showPrice(data.price,data.discount_price).price}}">
</l-price>
<l-price  
    wx:if="{
   
   {p.cutPrice(data.price,data.discount_price).display}}" 
    deleted 
    value="{
   
   {p.cutPrice(data.price,data.discount_price).price}}">
</l-price>

<wxs module="p">
// 如果不进行函数处理,当只有一个原价时,它会将原价也打上删除线,所以必须用该逻辑实现

// 最终要显示的价格
function showPrice(price, discountPrice) {
    if (!discountPrice) {
        return {
            price: price,
            display: true
        }
    } else {
        return {
            price: discountPrice,
            display: true
        }
    }
}

// 显示有切割线的那个价格
function cutPrice(price, discountPrice) {
    if (discountPrice) {
        return {
            price: price,
            display: true
        }
    } else {
        return {
            price: '',
            display: false
        }
    }
}
// 导出这两个函数
module.exports = {
    showPrice: showPrice,
    cutPrice: cutPrice
}
</wxs>

추천

출처blog.csdn.net/weixin_60414376/article/details/126918949