动态引用本地资源

利用@mpxjs/url-loader,配合mpx提供的计算属性,实现在运行阶段动态设置图片

文件目录

  1. component
  2. │-- index.mpx
  3. │-- dark.png
  4. │-- light.png

webpack.config.js

  1. webpackconfig = {
  2. module: {
  3. rules: [
  4. {
  5. test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
  6. loader: MpxWebpackPlugin.urlLoader({
  7. name: 'img/[name].[ext]'
  8. })
  9. }
  10. ]
  11. }
  12. }

index.mpx

  1. <template>
  2. <view>
  3. <image src='{{dynamicSrc}}'/>
  4. <view class="container" style='{{dynamicStyle}}'>i have a background image</view>
  5. <button bindtap="clickHandler">click me to change</button>
  6. </view>
  7. </template>
  8. <script>
  9. import {createPage} from '@mpxjs/core'
  10. // 如果是有限张图片
  11. import dark from './dark.png'
  12. import light from './light.png'
  13. createPage({
  14. data: {
  15. count: 0,
  16. imageId: '1'
  17. },
  18. computed: {
  19. dynamicSrc() {
  20. return (this.count % 2 === 0) ? dark : light
  21. },
  22. dynamicStyle() {
  23. let url = (this.count % 2 !== 0) ? dark : light
  24. return `background-image: url(${url})`
  25. },
  26. background () {
  27. // 如果期望整个bgs文件夹里的图片都被纳入
  28. return require('./bgs/' + this.imageId + '.jpg')
  29. }
  30. },
  31. methods: {
  32. clickHandler() {
  33. this.count++
  34. }
  35. }
  36. })
  37. </script>
  38. <style lang="stylus">
  39. .container
  40. height: 150px
  41. </style>

通过点击button,两个元素的图片会动态变化