前言:一个函数的参数越少越好,并不是参数少或不传更优雅,而是有其他方案来优化长参数。一个函数的参数尽量不要超过3个,如果超过了这个限制,那么代码的坏味道就产生了。
一、整合参数
如果参数很多,那么第一就要考虑,这些参数是否存在关联?若存在是否可以归为一组?
badCase:
function updateElements(element1, text1, element2, text2, element3, text3) {  element1.innerText = text1;  element2.innerText = text2;  element3.innerText = text3;  
}  // 使用该函数  
const header = document.getElementById('header');  
const mainContent = document.getElementById('main-content');  
const footer = document.getElementById('footer');  updateElements(header, 'Welcome!', mainContent, 'This is the main content.', footer, 'Goodbye!');goodCase:
function updateElements(elements) {  for (const key in elements) {  if (elements.hasOwnProperty(key) && document.getElementById(key)) {  const element = document.getElementById(key);  element.innerText = elements[key];  }  }  
}  // 使用该函数  
updateElements({  'header': 'Welcome!',  'main-content': 'This is the main content.',  'footer': 'Goodbye!'  
});二、避免静态数据做参数传递
静态的变量尽量直接使用,避免产生多余的参数。
badCase:
created () {this.getUserInfo(this.$router.query.id)
},methods: {getUserInfo(id) {axios.get('/user', {params: {id}})}
}goodCase:
created () {this.getUserInfo()
},methods: {getUserInfo() {axios.get('/user', {params: {id: this.$router.query.id || ''}})}
}三、组件中的父传子的参数较多
避免父传子的参数过多
badCase:
<template>  <div>  <ChildComponent :name="name" :email="email" :age="age" :theme="theme" :notifications="notifications" :language="language" /> </div>  
</template>  <script>  
import ChildComponent from './ChildComponent.vue';  export default {  components: {  ChildComponent  },  data() {  return {  name: 'John Doe',  email: 'john.doe@example.com',  age: 30   theme: 'dark',  notifications: true,  language: 'en'  }  };  
}  
</script>goodCase:
<template>  <div>  <ChildComponent :userInfo="userInfo" :userSettings="userSettings" />  </div>  
</template>  <script>  
import ChildComponent from './ChildComponent.vue';  export default {  components: {  ChildComponent  },  data() {  return {  userInfo: {  name: 'John Doe',  email: 'john.doe@example.com',  age: 30  },  userSettings: {  theme: 'dark',  notifications: true,  language: 'en'  }  };  }  
}  
</script>四、子组件中需要父组件的所有属性
    <custom-input v-bind="$attrs" />