企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持知识库和私有化部署方案 广告
7.4.1.组件结构化 ``` <template lang="html"> <div class="Ranger__Wrapper"> <!-- ... --> </div> </template> <script type="text/javascript"> export default { // 不要忘记了 name 属性 name: 'RangeSlider', // 使用其它组件 components: {}, // 使用组件 mixins 共享通用功能 mixins: [], // 组成新的组件 extends: {}, // 组件属性、变量 props: { bar: {}, // 按字母顺序 foo: {}, fooBar: {}, }, // 变量 data() { }, computed: {}, // 方法 watch: {}, methods: {}, // 生命周期函数 beforeCreate() { }, mounted() { }, }; </script> <style> /* 尽量不要使用scoped */ .Ranger__Wrapper { /* ... */ } </style> ``` 7.4.2.为组件样式设置作用域 对于组件库,选用基于 class 的策略而不是 scoped 特性。优先级别: * Class样式名使用组件名。 * 使用 CSS Modules * 使用 \`scoped\` 特性 | | | | --- | --- | ``` <!-- 使用 CSS Modules --> <template> <button :class="[$style.button, $style.buttonClose]">X</button> </template> <style module> .button { border: none; border-radius: 2px; } .buttonClose { background-color: red; } </style> ``` ``` <!-- 使用 CSS Modules --> <style module> .button { border: none; border-radius: 2px; } .buttonClose { background-color: red; } </style> <template> <button class="c-Button c-Button--close">X</button> </template> <!-- 使用 BEM 约定 --> <style> .c-Button { border: none; border-radius: 2px; } .c-Button--close { background-color: red; } </style> ``` 7.4.3.组件 props 原子化 7.4.4.组件的每一个属性单独使用一个 props,并且使用函数或是原始类型的值。 ``` <!-- 推荐 --> <range-slider :values="[10, 20]" :min="0" :max="100" :step="5" @on-slide="updateInputs" @on-end="updateResults"> </range-slider> <!-- 避免 --> <range-slider :config="complexConfigObject"></range-slider> ``` 7.4.5.验证组件的 props 提供默认值。 使用 type 属性校验类型。 使用 props 之前先检查该 prop 是否存在。 验证组件的 props ``` <template> <input type="range" v-model="value" :max="max" :min="min"> </template> <script type="text/javascript"> export default { props: { max: { type: Number, // 这里添加了数字类型的校验 default() { return 10; }, }, min: { type: Number, default() { return 0; }, }, value: { type: Number, default() { return 4; }, }, }, }; </script> ``` 7.4.6.组件事件命名 1、事件名也使用连字符命名。 2、一个事件的名字对应组件外的一组意义操作,如:upload-success、upload-error 以及 dropzone-upload-success、dropzone-upload-error 3、事件命名应该以动词(如 client-api-load) 或是 名词(如 drive-upload-success)结尾。 7.4.7.避免 this.$parent 通过 props 将值传递给子组件。 通过 props 传递回调函数给子组件来达到调用父组件方法的目的。 通过在子组件触发事件来通知父组件。 7.4.8.谨慎使用 this.$refs Props向下传递,事件向上传递!。 关注于组件本身的目的。 拒绝定制代码。 当需要操作 DOM 无法通过指令来做的时候可使用 this.$ref。 避免使用document.getElement*、document.queryElement。 拒绝使用JQuery。 ``` <!-- 推荐,并未使用 this.$refs --> <range :max="max" :min="min" :step="1" @current-value="currentValue"> 通过组件的emit </range> <!-- 使用 this.$refs 的适用情况--> <modal ref="basicModal"> <h4>Basic Modal</h4> <button class="primary" @click="$refs.basicModal.hide()">Close</button> </modal> <button @click="$refs.basicModal.open()">Open modal</button> ```