条件注释实现跨端兼容

条件编译是用特殊的注释作为标记,在编译时根据这些特殊的注释,将注释里面的代码编译到不同平台。
写法:以#fidef 加平台标识 开头,以#endif结尾。
image.png

组件的条件注释

代码演示:

  1. <template>
  2. <view>
  3. <button type="default" @click='chooseImg'>上传图片</button>
  4. <image v-for='item in imgArr' :src="item" @click='previewImg(item)'></image>
  5. <!-- #ifdef H5-->
  6. <view>
  7. 我希望只在h5页面中看见
  8. </view>
  9. <!-- #endif -->
  10. <!-- #ifdef MP-WEIXIN-->
  11. <view>
  12. 我希望只在微信小程序中看见
  13. </view>
  14. <!-- #endif -->
  15. </view>
  16. </template>
  17. <script>
  18. export default {
  19. data() {
  20. return {
  21. imgArr:[]
  22. }
  23. },
  24. methods: {
  25. chooseImg(){
  26. uni.chooseImage({
  27. count:5,//限制上传图片的数量
  28. success:res=>{
  29. this.imgArr = res.tempFilePaths
  30. }
  31. })
  32. },
  33. onLoad(){
  34. //#ifdef H5
  35. console.log('我希望h5中打印')
  36. //#endif
  37. //#ifdef MP-WEIXIN
  38. console.log('我希望在微信小程序打印')
  39. //#endif
  40. },
  41. previewImg(current){
  42. //console.log(current) 拿到相应的图片路径
  43. uni.previewImage({
  44. current,
  45. urls:this.imgArr,
  46. loop:true,
  47. indicator:'number'
  48. })
  49. }
  50. }
  51. }
  52. </script>
  53. <style>
  54. /* h5中的样式 */
  55. /* #ifdef H5 */
  56. view{
  57. color:hotpink;
  58. }
  59. /* #endif */
  60. /* #ifdef MP-WEIXIN */
  61. view{
  62. color:blue;
  63. }
  64. /* #endif */
  65. </style>
<!-- #ifdef H5-->
        <view>
            我希望只在h5页面中看见
        </view>
<!-- #endif -->

模板以及样式以及js都可以这样注释!