动态引用本地资源
利用@mpxjs/url-loader
,配合mpx提供的计算属性
,实现在运行阶段动态设置图片
文件目录
component
│-- index.mpx
│-- dark.png
│-- light.png
webpack.config.js
webpackconfig = {
module: {
rules: [
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: MpxWebpackPlugin.urlLoader({
name: 'img/[name].[ext]'
})
}
]
}
}
index.mpx
<template>
<view>
<image src='{{dynamicSrc}}'/>
<view class="container" style='{{dynamicStyle}}'>i have a background image</view>
<button bindtap="clickHandler">click me to change</button>
</view>
</template>
<script>
import {createPage} from '@mpxjs/core'
// 如果是有限张图片
import dark from './dark.png'
import light from './light.png'
createPage({
data: {
count: 0,
imageId: '1'
},
computed: {
dynamicSrc() {
return (this.count % 2 === 0) ? dark : light
},
dynamicStyle() {
let url = (this.count % 2 !== 0) ? dark : light
return `background-image: url(${url})`
},
background () {
// 如果期望整个bgs文件夹里的图片都被纳入
return require('./bgs/' + this.imageId + '.jpg')
}
},
methods: {
clickHandler() {
this.count++
}
}
})
</script>
<style lang="stylus">
.container
height: 150px
</style>
通过点击button,两个元素的图片会动态变化