Possible problems and solutions in Vue projects

Compared with other frameworks, Vue is more likely to produce unqualified code; because the options in Vue are a large object, many detections of js itself are invalid. For example, if a function is not used, it will "turn gray" , there are fewer code prompts in the template, more mixins, etc.; when encountering unqualified code, most people’s first reaction is who wrote such bad code. In fact, most people in most companies have at least written some bad code. It is normal to have qualified code and unqualified code. The problem is how to quickly sort out the business logic and prevent bugs from being caused when iterating new requirements. When there is enough spare capacity, partial reconstruction can be carried out and the Shishan code can be progressively optimized;

Then, next you can look at the areas where the front-end project is unqualified, which are probably the following:

1. The directory is messy

src/
├── App.vue
├── api
├── components
├── constants
├── main.js
├── pages
├── router
├── services
├── utils
│   └── hash.js
└── views

Take a look at the directory above. Views and pages have similar meanings. They both refer to the page corresponding to the route. API and services are also similar. They both store the encapsulation of the back-end interface. The existence of these folders at the same time means that there is no such folder in the early stage of the project. Standards, everyone develops according to their own standards, which leads to some people writing their pages in views and some writing them in pages. It is recommended that only one of these directories with similar meanings be kept;

The harm is that the people who take over the work will frequently switch folders to see the logic of different pages, and they will not know which folder they should use to develop their own pages in the future, leading to a vicious cycle.

2. Components are not split

Vue combines template, script, and style in a .vue file, which naturally results in a very large number of lines in each .vue file, making it difficult to maintain. One of the most obvious problems in Vue2 is thousands of lines, or even Thousands of lines of code, in professional terms, do not comply with the single responsibility principle. A component should only do one thing, a function should only handle one logic, and the rest of the logic is left to other functions or components; always keep this in mind The "SOLID" principle is the first way to stay away from the shit mountain;

3. Complex expressions

<div
    class="files"
    :class="{ disabled: !isAllowRead && hasNotPassed && aaa && (bbb || ccc) }"
    @click="toDetail()"
  >
  <a/>
  <b v-if="!isAllowRead && hasNotPassed && aaa && (bbb || ccc)"/>
 </div>

Looking at this piece of code, in order to determine a disabled state, a large number of operators are used, resulting in unclear logic. When encountering similar logic, I have to ctrl cv on component b below, and I have become a cv engineer. This is correct. The approach is to put it into the calculated attributes for judgment, and split the calculated attributes according to the logic used later:

<div
        class="files"
        :class="{ disabled: isFileDisabled }"
        @click="toDetail()"
      >
      <a/>
      <b v-if="isFileDisabled"/>
     </div>
     <script>
         export default {
      
      
             // 此处省略...
             computed: {
      
      
              isFileDisabled(){
      
      
                 return !isAllowRead && hasNotPassed && aaa && (bbb || ccc)
              }
             }
         }
     </script>

Of course, the calculated property isFileDisabled can also be split into multiple properties. This mainly depends on subsequent reuse.

4. A large number of duplicate nodes

 <div>
    <span v-for="item in textConfigs" :key="item.valueKey">{
   
   {
      response[item.valueKey]
    }}</span>
  </div>
  
  data() {
    return {
     textConfigs: [
        { label: "性别", valueKey: "name" },
        { label: "年龄", valueKey: "age" },
        { label: "性别", valueKey: "gender" },
        { label: "身高", valueKey: "height" },
        { label: "体重", valueKey: "weight" },
        { label: "爱好", valueKey: "habit" }
      ]
    };
  },

五、if else switch

if(!values.username){
    this.$message.error("用户名不能为空")
} else if(!values.password){
    this.$message.error("密码不能为空")
} else if(!values.phoneNumber){
    this.$message.error("手机号不能为空")
} else {
    this.submit();
}

Some people may say that the above code has clear semantics and is not written well enough? However, if more verification conditions need to be added, developers have to invade specific methods to modify the code. After optimization using the strategy mode, the verification conditions can be decoupled from the specific judgment logic. When additional verification conditions need to be added, they can be modified directly. Just use an array:

const validators = [
  { message: "用户名不能为空", required: true, key: "username" },
  { message: "密码不能为空", required: true, key: "password" },
  { message: "手机号不能为空", required: true, key: "phoneNumber" }
];

export default {
  methods: {
    validator(values) {
      const result = validators.some(el => {
        if (el.required && !values[el.key]) {
          this.$message.error(el.message);
          return true;
        }
      });
      return result;
    },
    submit(values) {
      if (this.validator(values)) {
        return;
      }

      // ... 调用接口
    }
  }
};

6. Incorrect use of Mixins

// a.mixin.js
export default {
  data() {
    return {
      username: "",
      password: "",
      age: 18
    };
  },
  created() {
    this.fetchUserInfo();
  },
  methods: {
    fetchUserInfo() {}
  }
};

// b.mixin.js
export default {
    data(){
        return {
            height:'',
            weight:''
        }
    },
    created(){
        this.fetchBodyFat();
    },
    methods:{
        fetchBodyFat(){

        }
    }
}

// c.vue
const DEGREEMAP = {
    doctor:'博士'
}
export default {
    mixins:[a,b],
    data(){
        return {
            degree:DEGREEMAP.doctor
        }
    },
    created(){
        this.log()
    },
    methods:{
        log(){
            if(this.age < 30 && this.height>180 && this.degree===DEGREEMAP.doctor){
                alert("真牛!")
            }
        }
    }
}

Here a and b provide some data, and finally use them in c.vue. This will easily cause problems such as variable coverage and unknown origins. If you must use vue2, this situation is unavoidable and you can only try to reduce component duplication. The degree of coupling of data in mixins.

Guess you like

Origin blog.csdn.net/huangzhixin1996/article/details/132955223