vue 的奇技淫巧
全局引入 Less 变量
- 定义一个
variable.less
,将你想用的全局变量写入其中
@primary-color: #9a69ec;
@link-color: #9a69ec;
@tip-color: #3c67bd;
@success-color: #52c41a;
@warning-color: #faad14;
@error-color: #f5222d;
1
2
3
4
5
6
2
3
4
5
6
安装
style-resources-loader
加载器:vue add style-resources-loader
,预处理器选择Less
将
variable.less
配置到加载器在vue.config.js
中生成的代码片段中
const path = require('path')
module.exports = {
pluginOptions: {
'style-resources-loader': {
preProcessor: 'less',
patterns: [path.resolve(__dirname, '{variable_file_path}/variable.less')]
}
}
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
内联样式 style、class 三元表达式
style
三元表达式:<p :style="{'color': (check == true ? '#fff': '#333')}"></p>
class
三元表达式:<i class="iconfont " :class="[type == 'password' ? 'icon-bukejian': 'icon-kejian']"></i>
动态引入资源
- 定义一个
util
函数
const LoadRes = (src) => {
return new Promise((resolve, reject) => {
const script = document.createElement('script')
script.type = 'text/javascript'
script.onload = () => {
resolve()
}
script.onerror = () => {
reject(new Error('第三方类库加载失败'))
}
script.src = src
document.getElementsByTagName('body')[0].appendChild(script)
})
}
export default {
LoadRes
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
- 使用
<script>
import util from '@/utils/util'
export default {
name: 'Util',
mounted () {
util.LoadRes('https://foo.bar/demo.js').then(() => {
// TODO
})
}
}
</script>
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
获取 DOM 节点
在
Vue
中,只能在mounted
及其之后的钩子函数中进行DOM
操作,因为mounted
时才完成DOM
挂载选择器获取
<template>
<div>
<canvas id="cvs">
</div>
</template>
<script>
export default {
mounted () {
let canvas = document.querySelector('#cvs')
}
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
ref
获取
<template>
<div>
<canvas ref="cvs">
</div>
</template>
<script>
export default {
mounted () {
let canvas = this.$refs.cvs
}
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
获取请求参数
项目内页面之间跳转
跳转
Script
脚本
this.$router.push({ name: 'Index', // 等价于 path: 'index' query: { role: params.role } });
1
2
3
4
5
6Template
模板
<!-- 等价于 name: 'Detail' --> <router-link :to="{ path: '/detail', query: { role: params.role } }"> <div></div> </router-link>
1
2
3
4
5
6
7
8
9接收
public created(): void { this.role = this.$route.query.role; }
1
2
3外部跳转
Vue
项目
const getUrlParam = () => {
// 获取当前 url
const u: string = window.location.href;
// 获取 #/ 之前的字符串
const r: string = u.split('#')[0];
// 获取 ? 之后的参数字符串
const l: string = r.split('?')[1];
// 参数字符串分割为数组
const params: string[] = l.split('&');
const param: any = {};
// 遍历数组,拿到 json 对象
for (const item of params) {
param[item.split('=')[0]] = item.split('=')[1];
}
return param;
};
export default {
getUrlParam,
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21