Tip 3 The splicing method of front-end and back-end interactive picture addresses of vue3 project axios

Generally speaking, there are two storage methods for pictures:

1. The backend transmits the complete online address

The list item img is a complete image online address (https://www.xxx/img/1.jpg), the front-end can read the array directly from the backend, and the url of img can be rendered directly.

2. The picture is stored in the front end

When the picture is stored in the front-end public folder, the back-end picture address is likely to be the name of the picture, not the path, because the path is the relative path of the front-end picture storage.

#python
[{
    
    "id":1,"content":"xxxx","url":"9.png"},{
    
    },{
    
    }]

At this time, the front end needs to connect to the back end to pass the value to splice the path.

Stitching path method:

 created(){
    
    
		  //1.初始化函数里:从后端获取分类的数据。
		  //用到axios 从后端直接获取,不用传参。用get接收即可。
		   this.getdata()  
	  },
	  methods:{
    
    
		  getdata(){
    
    
				var that=this;
				this.$axios.get("http://127.0.0.1:8000/v3baisort/")
				.then(function(data){
    
    
				// 2. 由于后端图片地址不是在线的,图片存储在项目中,
				// 所以后端只是图片名,需要在这里拼接一下图片路径.	
				  for(var i = 0; i < data["data"].length; i++){
    
    
				  var url1=data["data"][i].url
				  // 1)找到放图片路径的地方 拼接后端的图片名。
				  var imgurl=require('../../../public/img/goods/goodssort/'+url1)
					// 2)给后端数组的图片url重新赋值
				  data["data"][i].url=imgurl
				  }
					// 3)把后端数据赋给本页面catelist
				 that.catelist=data["data"]
				 
				}).catch(function(error){
    
    
					alert(error)
					})
				},
		  
	  } 

It seems to be cumbersome to write like this, there is an easier splicing method:

Directly use axios to read the name of the picture. Isn't it better to bind the src on the img tag when rendering, and splice directly on the src?

If you think this way, you should pay attention, img will not recognize this dynamic binding:

<img :src="'../../public/img'+item.url" /><br>

The src binding will be parsed into a pure string, which can only be packaged through require() in axios, and then displayed after splicing.

How to use require:

require process image address

Guess you like

Origin blog.csdn.net/yangyangdt/article/details/122464187