异步组件:按需加载组件
mixins:混入
scoped:样式私有化
还是有点抽象,根据一个实际的业务需求来看一下具体的使用。绑定用户手机号:A页面有一个按钮,点击进入B页面,如果未绑定过手机 则展示绑定相关的界面,如果已经绑定过,则展示修改相关的页面。绑定和修改都有一部分相同的功能,比如获取用户名和发送验证码功能,如何实现
1.异步组件
进入B页面以后,要么绑定要么修改,并且不存在其他操作可以切换两种状态,所以每次进入之前通过判断是绑定还是修改,只需要加载对应的组件即可
<div>
<component :is="curPage"></component>
</div>
export default {
name: 'bind-phone',
components: {
TableTitle,
'createPhone': () => import('./modules/create-phone'),
'resetPhone': () => import('./modules/reset-phone'),
},
data() {
return {
curPage: '', //当前页面
curType: '', //当前页面的状态
};
},
methods: {
//当前页面的状态
getCurType() {
let search = this.$_lib.getSearch('type');
this.getCurInfo(search);
},
//处理当前页面一些基本信息
getCurInfo(curType) {
let oo = {
create_phone: {
component: 'createPhone',
title: '绑定手机号',
},
reset_phone: {
component: 'resetPhone',
title: '绑定手机号',
},
};
let cur_info = oo[curType];
this.curPage = cur_info.component;
}
},
created() {
this.getCurType();
},
};
2.混入
绑定和修改都有部分相同的功能,所以可以通过混入mixins的方式将这些部分提到一个js里面去
混入的先执行,methods、watch这些会混合为一个对象,如果有同名键名以组件内部的优先
import {bindPhone} from "./bind-phone.js";
export default {
name: 'create-phone',
components: {UserPublic},
mixins: [bindPhone],
methods: {
},
};
3.scoped
scoped会增加复杂度,为什么呢,来看一下scoped的实现
button组件
<template>
<div class="button-warp">
<button class="button">text</button>
</div>
</template>
...
<style scoped>
.button-warp{
display:inline-block;
}
.button{
padding: 5px 10px;
font-size: 12px;
border-radus: 2px;
}
</style>
浏览器渲染后
<div data-v-2311c06a class="button-warp">
<button data-v-2311c06a class="button">text</button>
</div>
.button-warp[data-v-2311c06a]{
display:inline-block;
}
.button[data-v-2311c06a]{
padding: 5px 10px;
font-size: 12px;
border-radus: 2px;
}
可以看到 给dom节点加了一个不重复的data属性来表示唯一性,在css选择器末尾添加了data选择器来实现私有化
虽然scoped实现组件样式私有化,但是由于css优先级的问题,使用scoped导致组件样式权重加重,外部修改组件内部样式需要更高的权重,层级过深会极大增加复杂度
scoped使用:组件样式使用场景单一,几乎不需要来自外部的样式修改
建议给组件最外层标签添加与name相同的class,其他样式通过嵌套的方式写在里面
如果当前组件的css只用于当前组件的话,建议直接写在当前组件style标签内,不要通过@import的方式来引入