Vue computed with parameters

Vue computed with parameters

In general, we cannot directly pass parameters when using computed properties in Vue.

方法:如果有传参数的需求可以通过闭包函数(也叫匿名函数)来实现。

For example, it is necessary to dynamically change the width of the div through the size of the data

 <div v-for="(item, index) in mydata" :key="index">
 	<span :style="barWidth(item)"></span>
 </div>
<script>
export default {
    
    
	data(){
    
    
		retrun {
    
    
			mydata:[110,120,130,140,150,160,170,180,190,1100]
		}
	}
	computed: {
    
    
	    barWidth() {
    
    
	      return function (item) {
    
               //主要思想是通过此处的闭包来实现
	        const style = {
    
    };
	        style.height = item + 'px';
	        return style;
	      };
	    },
  },
}
</script>

If it is used in the template, the same reason

 <div>Computed some message: {
    
    {
    
     myComputed('55555') }}</div>
computed: {
    
    
	     myComputed: function () {
    
    
		      return (parameter)=>{
    
    
		   	   		return  this.message + '666666'
			 } 
	    }
  },

Guess you like

Origin blog.csdn.net/qq_58648235/article/details/130139294