Vue-在data中引入静态图片路径

本文介绍了在Vue.js项目中如何正确引入和使用静态图片资源,包括直接在template中写入路径、在data中定义、使用import和require的方式。同时,讨论了在使用props和attrs时的困惑,并提供了相关代码示例。通过这些方法,开发者可以解决图片路径识别不了的问题。
摘要由CSDN通过智能技术生成

请添加图片描述

在data中引入静态图片路径

首先tempate中内容都一样:

      <template slot="pic" slot-scope="{ row }">
        <img :src="row.pic" alt="" height="100px" width="100px">
      </template>

图片如果直接写在template中:

<img src="../../../../assets/images/mapicon.png" alt="查看"/>

data中直接引入图片的静态地址:

        {
          id: '2',
          name: '王冬冬',
          pic: '../assert/images/4.jpg',
          price: '43.65',
          checked: true,
          count: 2
        },

很奇怪的是,在我这里引入这个不管用,识别不了路径,具体什么原因不清楚,但是我看到很多博主都有阐述,所以这里记录一下。

import直接导入:

首先将图片放在assets文件夹下,然后引用:

import smile from '../assets/images/3.jpg'

data中:

        {
          id: '0',
          name: '王小明',
          pic: smile,
          price: '43.65',
          checked: false,
          count: 0
        },

require导入:

          pic: require('../assets/images/5.jpg'),

attrs:

        {
          title: '图片',
          key: 'pic',
          render: (h, params) => {
            return h('img', {
              attrs: {
                src: params.row.pic
              },
              style: {
                height: '100px',
                width: '100px'
              }
            })
          },
          slot: 'pic'
        },

附上源码:

<template>
  <div class="container">
    <h1>LOL英雄皮肤购物车</h1>
    <router-link to="/about">About</router-link>
    <Table :columns="columns1" :data="data1">
      <template v-slot="{row}">
        <Checkbox v-model="row.checked">Checkbox</Checkbox>
      </template>
      <template slot="pic" slot-scope="{ row }">
        <img :src="row.pic" alt="" height="100px" width="100px">
      </template>
      <template slot="total" slot-scope="{ row }">
        <span>{{ conputedTotal(row.price, row.count) }}</span>
      </template>
      <template slot="action" slot-scope="{ row, index }">
        <Button type="error" @click="remove(index)">删除</Button>
      </template>
    </Table>
    <div class="footer">
      <h1>总计:{{ total }}</h1>
      <p>
        <Button type="success" @click="submit(index) ">微信支付</Button>
      </p>
    </div>
  </div>
</template>
<script>
import BigNumber from 'bignumber.js'
import smile from '../assets/images/3.jpg'

export default {
  name: 'Home',
  data () {
    return {
      indeterminate: true,
      checkAll: false,
      checkAllGroup: ['香蕉', '西瓜'],
      columns1: [
        {
          title: '全选',
          key: 'selection',
          type: ''
        },
        {
          title: '序号',
          key: 'name',
          type: 'index'
        },
        {
          title: '名字',
          key: 'name',
          type: ''
        },
        {
          title: '图片',
          key: 'pic',
          render: (h, params) => {
            return h('img', {
              attrs: {
                src: params.row.pic
              },
              style: {
                height: '100px',
                width: '100px'
              }
            })
          },
          slot: 'pic'
        },
        {
          title: '单价',
          key: 'price'
        },
        {
          title: '商品总价',
          slot: 'total'
        },
        {
          title: '数量',
          key: 'count',
          render: (h, params) => {
            return h('div', [
              h('InputNumber', {
                props: {
                  max: 100,
                  min: 0,
                  value: params.row.count
                },
                on: {
                  'on-change': (value) => {
                    console.log(value)
                    this.data1[params.index].count = value
                  }
                }
              })
            ])
          }
        },
        {
          title: '操作',
          key: 'address',
          slot: 'action'
        }
      ],
      data1: [
        {
          id: '0',
          name: '王小明',
          pic: smile,
          price: '43.65',
          checked: false,
          count: 0
        },
        {
          id: '1',
          name: '王筱筱',
          pic: 'https://img2.baidu.com/it/u=1070003001,653753576&fm=26&fmt=auto&gp=0.jpg',
          price: '43.65',
          checked: false,
          count: 0
        },
        {
          id: '2',
          name: '王冬冬',
          pic: '../assert/images/4.jpg',
          price: '43.65',
          checked: true,
          count: 2
        },
        {
          id: '3',
          name: '周小伟',
          pic: require('../assets/images/5.jpg'),
          price: '43.65',
          checked: true,
          count: 0
        },
        {
          id: '4',
          name: '周小深',
          price: '52.13',
          pic: smile,
          checked: true,
          count: 0
        },
        {
          id: '5',
          name: '小小苏',
          pic: require('../assets/images/5.jpg'),
          price: '13.14',
          checked: true,
          count: 0
        }
      ]
    }
  },
  methods: {
    conputedTotal (price, count) {
      return new BigNumber(price).multipliedBy(count).toFixed(2)
    },
    remove (index) {
      this.$Modal.confirm({
        title: '警告',
        content: '确认删除?',
        onOk: () => {
          this.data1.splice(index, 1)
          // this.$Message.info('点击了确定')
        },
        onCancel: () => {
          // this.$Message.info('点击了取消')
        }
      })
    },
    submit () {
      this.$Message.success('提交成功!')
      // eslint-disable-next-line no-undef
    },
    // 商品选择框
    handleCheck (row, index) {
      var check = [] // 保存中间层是否被选中的布尔值
      this.data.forEach((row, index) => {
        if (row.checked) {
          var bool = row.checked.every(crow => crow.checked)
          if (bool) {
            row.checked = true
          } else {
            row.checked = false
          }
          check.push(bool)
        }
      })
    }
  },
  computed: {
    total () {
      const num = this.data1.reduce((a, b) => {
        return new BigNumber(a).plus(new BigNumber(b.count).multipliedBy(b.price))
      }, 0)
      return new BigNumber(num).toFixed(2)
    }
  },
  mounted () {
    this.data1.forEach(row => {
      this.$set(row, 'checked', false) // Vue 解决不能检测到对象属性的添加或删除
      // row.checked = false; //如果为真实数据直接设置的对象改变值不会更新视图
      if (row.checked) {
        row.checked.forEach((crow) => {
          this.$set(crow, 'checked', false)
          // crow.checked = false;
        })
      }
    })
  }
}
</script>
<style scoped>
.container {
  width: 1224px;
  margin: 0 auto;
  text-align: center;
}

.footer {
  text-align: right;
  margin-bottom: 300px;
}
</style>

成品截图:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ymUH27ZG-1630466248210)(C:\Users\Melody\AppData\Roaming\Typora\typora-user-images\image-20210901111556326.png)]

办法很多,但是sttrs和props的区别,我看不出来,

下面的这段代码搞不懂:

{
  title: '头像', key: 'headimg',
  render: (h, params) => {
    console.log(params.row)
    return h('div', {
      attrs: {
        style: 'width: 40px;height: 40px;'
      },
    }, [
        h('img', {
          props: {
            type: 'primary',
            size: 'small'
          },
          attrs: {
            src: params.row.headimg, style: 'width: 40px;height: 40px;border-radius: 2px;'
          },
          style: {
          },
        }),
      ]);
  }
},

propsattrs,都用到了,这里有介绍博客,但是没太读懂:
https://blog.csdn.net/wennianzhu/article/details/107065730

  • 6
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue3,本地图片引入方式有一些变化。在Vite,使用import语法来引入本地图片是不可行的,因为Vite不支持require。官方文档提供了两种解决方案。 第一种解决方案是将资源引入为URL。你可以使用import语法来引入图片,并将其赋值给一个变量,然后在模板使用这个变量作为图片的src属性。例如: ```javascript import chatHealth from '@/assets/chat-health.png' <img :src="chatHealth" alt="" /> ``` 这种方法在本地运行时可以加载出图片,但是在真实环境(测试/线上),可能会出现找不到文件的问题。这是因为打包后的文件路径与实际路径不匹配。你可以检查打包后的文件,看看是否包含了这个图片。如果没有,可能是因为Vite没有正确加载这个图片。需要进一步检查你的操作是否正确。 第二种解决方案是使用相对路径引入图片。你可以直接在模板使用相对路径引入图片,而不是使用import语法。例如: ```html <img src="../assets/images/chat-health.png" alt=""> ``` 这种方法在本地运行和真实环境都可以正常加载图片。 总结起来,Vue3本地图片引入方式在Vite有一些变化。你可以尝试使用import语法将图片引入为URL,或者直接在模板使用相对路径引入图片。具体选择哪种方式取决于你的需求和项目配置。 #### 引用[.reference_title] - *1* [vue3 vite版本 引入本地静态图片的方式](https://blog.csdn.net/weixin_42211816/article/details/122731618)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [vue3:加载本地图片静态资源](https://blog.csdn.net/weixin_43972437/article/details/129028118)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Coisini_甜柚か

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值