适用阅读对象:需要兼顾前端的C#后端开发人员(基础笔记)
一、后端交互-获取实体数据
1.post
2.get 或 delete
3.catch结构
4.修改全局变量(更新下拉框)
二、变量
1.声明
2.作用域
三、字符串的处理
四、数组(列表)的处理
1.数组中的Select语法(提取特定字段到新数组)
(1) SELECT一个列表
(2) SELECT一个实体列表
(3) 利用SELECT批修改字段内容,增加字段
2.数组中的foreach语法
1.for循环基础
2.for循环添加实体
3.数组的Length语法
4.数组的First语法
1.基础写法
2.封装写法
5.数组的Where语法
6.数组中的Contais语法
7.数组的Add语法
8.数组的Distinct方法
9.数组的OrderBy方法
10.数组的Intersect方法
五、变量
1.单变量的IsNullOrEmpty方法
2.多变量的空判断
1.其中一个空
2.全空
3.保留小数的Math.Round()方法
六、 字典
七、其他语法
1.展开运算符(三个点)
八、快捷键
1.批量格式化文档
附录一、Vue易犯错误:
1.变量声明和方法调用
2.静态页面运行和debug调试
3.组件问题
使用前导入:import { axios }
写法一
axios.post(this.requestUrl, {
id: 1,
name: 'Alice',
list: [1, 2, 3]
})
.then((res) => {
// 检查响应是否为 null
if (res === null)
{
throw new Error('服务器未返回有效数据')
}
if (res.result.success === true)
{
this.$notification.success({ message: '操作成功!' })
}
else
{
this.$notification.error({ message: '操作失败!${res.result.msg}!' })
}
})
.catch((error) => {
console.error('请求失败:', error.message)
});
写法二
const params = {
id: 1,
name: 'Alice',
list: [1, 2, 3]
};
axios.post(this.requestUrl, params)
.then((res) => {
// 处理响应数据
});
注意:get和post不一样,这里需要加上{ params:{ //这里写入参 } }
如果是delete,将下面的get改一下即可
axios.get(this.requestUrl, {
params: {
TaskName: '任务',
TaskCode: this.taskCode,
}
})
.then((res) => {
// 检查响应是否为 null
if (res === null)
{
throw new Error('服务器未返回有效数据')
}
if (res.result.success === true)
{
this.$notification.success({ message: '操作成功!' })
}
else
{
this.$notification.error({ message: '操作失败!${res.result.msg}!' })
}
})
.catch((error) => {
console.error('请求失败:', error.message)
});
直接加到post/get请求的后面
.then((res) => {
// 检查响应是否为 null
if (res === null)
{
// 如果响应为 null,抛出自定义错误并跳转到 catch 块
throw new Error('服务器未返回有效数据');
}
if (res.result.success === true)
{
this.$notification.success({ message: '操作成功!' })
}
else
{
this.$notification.error({ message: '操作失败!' })
}
})
.catch((error) => {
console.error('请求失败:', error.message);
});
【传入】DictData 【传出】data第1个元素
var str = '123'
var nums = 123
var array = [] //数组,例如 arr:[{ name:'susu',age:15},{ name:'linlin',age:18}]
var obejct =null //对象,例如 obj:{ name:'susu',age:15}
var bool = true
this变量需要在data中声明,其余可以在方法中直接使用var等关键字声明
Method() {
const d = 0; // 声明的变量 `d` 在最近一层的花括号内部有效
let a = 1; // 声明的变量 `a` 在最近一层的花括号内部有效
var b = 2; // 声明的变量 `b` 整个方法有效,即在 `Method` 方法内部有效
this.c = 3; // 使用 `this.c`,如果 `c` 已经在 `data` 对象中声明,它是全局对象的一个属性,因此在整个程序中都是有效的
}
var str = 'abcde'
var b = str.includes('de') //true
var c = str.split('c')[0] //'ab'
var sub = str.substring(1, 4); // 'bcd'
var trimmed = str.trim(); // 'abcde' 去除空格
let num = 123 //数字转化为字符串
let str2 = num.toString() // 使用 toString() 方法,注意是大写S
var num = '123'
var snum = parseInt(num, 10) //字符串转为十进制的int
const Code = 'abc'
console.log(`我的Code是: ${Code}`)//字符串拼接
--全局替换
path.replace(/\\/g, '/') //字符串中的所有反斜杠('\\')为斜杠('/')
path..replace(/a/g, 'b') //所有 a 替换为 b
【需求】提取所有 name 属性到一个新数组(this.details是一个列表)
const nameArray = this.details.map(item => item.name)
const newarray = this.details.map(item =>
({
label: item.name,
value: item.value
})
)
//如果标签和value是同一个值:
.map((x) => ({ label: x, value: x }))
【基础1】
var newarray = tablesource.map(item => ({
...item, // 保留原始对象的其它字段
alarmTime: item.alarmTime.replace('T', ' ') // 更改字段内容:替换 'T' 为空格
score: item.id < 5 ? 90 : 100 //新加一个字段:取值由id决定
}))
【基础2】自增id
var newarray = tablesource.map((item, index) => ({
id: index + 1 // 新的 id 从 1 开始自增
}));
for (let i = 0; i < list.length; i++) // 使用for循环遍历列表
{
var index = i //索引,从0开始
var item = list[i] //列表的每个实体
var name = item.name //访问列表中的name对应的数据
var value = item.value //如果是List<string>这种,就是var value = list[i]
}
//列表追加实体
var result = []
for (let i = 0; i < list.length; i++) {
var item = list[i]
var entity = {} // 初始化 entity 为空对象
entity.id = item.pid
entity.name = item.label
result.push(entity) //列表.add(实体)
}
console.log(result)//打印列表
//输出数组长度
const nameArrayLength = nameArray.length;
【情景】后端传入一个数组,存入list(id name)中,如何获取id=30的name的值呢
【严重警告】前端没有FirstOrDefault方法,获取实体后必须判断其情况!不可直接对象.属性(空引用直接报错)
【正确的例子】
const entity = list.find(x => x.id === 30)
if (entity)
{
console.log(entity.name) // 输出:Charlie
}
else
{
console.log('未找到匹配的 id')
}
【错误的例子】
const name = list.find(x => x.id === 30).name
console.log(name) //空引用,不报错,直接不运行后面的代码!
methods: {
FirstOrDefault(list, criteria) {
const entity = list.find(item => {
return Object.keys(criteria).every(key => {
return item[key] == criteria[key]; // 可以处理数字和字符串比较
});
});
this.result = entity || null; // 将找到的实体或 null 存入 result
if (entity) {
console.log('找到实体:', entity); // 输出找到的实体
return entity
} else {
console.log('未找到匹配的条件', criteria);
return null
}
}
}
// 示例使用
var result = this.FirstOrDefault(this.list, { id: '31', age: '19' }); // 根据 id 和 age 查找
//获取列表:details数组中的name字段包含xxx字符串的数组
var result = this.details.filter(item => item.name.includes('xxx'))
var result = this.details.filter(item => item.name==='John')
//包含字符A筛选
dataarray = dataarray.filter(x => x.includes('A'))
//includes方法支持数组筛选,注意是mainarray.inculudes(secondearray)
//C# var relist = dataarray.where(x=> list.Contains(x.key))
relist = relist.filter(x => list.includes(x.key))
//假设Data是一个有数据的数组
Data.push(30) //加入数字,相当于List<object>
Data.push({name: '123',value: 30]}) //加入实体,相当于List<Model> Model包含两个字段
list是一个数组(List<string>),去重方法:
var unique = [...new Set(list)]
//【备注】Set 自动去重,然后使用扩展运算符 ... 将其转换回数组
【需求】newarray2有很多字段,对value字段进行排序
newarray2.sort((a, b) => a.value.localeCompare(b.value)) //升序
newarray2.sort((a, b) => b.value.localeCompare(a.value)) //降序
取两个列表的交集
var Intersectlist = alist.filter(x => blist.includes(x))
【封装】
methods: {
IsNotNullNotUndefinedNotEmpty(value) {
return value !== null && typeof value !== 'undefined' && value !== ''
}
}
【调用】
//调用示例:
if (this.IsNotNullNotUndefinedNotEmpty(this.xxx))
{
console.log('该变量不是null 且 不是空字符串 且 不是未定义的');
}
【不封装好像可以直接用】
//js示例:
if (this.xxx)
{
console.log('该变量不是null 且 不是空字符串 且 不是未定义的');
}
//写在方法中:
IsNotNullOrEmpty(list) {
return list.every(item =>
item !== null &&
typeof item !== 'undefined' &&
item !== '' &&
(Array.isArray(item) ? item.length > 0 : true)
)
}
//调用示例
var myList=[ { key: 'value1' }, { key: 'value2' }, [], null]
var b = this.IsNotNullOrEmpty(myList) //输出False
优化前
if (
this.latitudeMin === null ||
this.latitudeMax === null ||
this.longitudeMin === null ||
this.longitudeMax === null
)
优化后
const { latitudeMin, latitudeMax, longitudeMin, longitudeMax } = this;
if ([latitudeMin, latitudeMax, longitudeMin, longitudeMax].some(x => x === null))
优化前
if (
this.latitudeMin !== null &&
this.latitudeMax !== null &&
this.longitudeMin !== null &&
this.longitudeMax !== null
)
优化后
const { latitudeMin, latitudeMax, longitudeMin, longitudeMax } = this;
if ([latitudeMin, latitudeMax, longitudeMin, longitudeMax].every(x => x !== null))
var a = 38;
var formattedA = a.toFixed(4); // "38.0000"
const polluCodeMap = { 'CO2': 'CO₂(ppm)', 'N2O': 'N₂O(ppb)', 'CH4': 'CH₄(ppb)', 'CO': 'CO(ppm)', 'SF6': 'SF6(ppb)', 'H2': 'H2(ppb)' }
const title = polluCodeMap[this.polluCode] || '(ppb)'//假设this.polluCode是入参,匹配不到返回'(ppb)'
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]
| 变量声明 | ① 使用全局变量不在data()声明 ② const定义后不可以再覆盖该值,若想修改用var声明 |
| 变量使用 | ①不加前缀:例如this.name,self.name 直接使用name ②不定义就使用:例如data(){}里面没有定义,函数内又不写var 直接用 |
| 方法调用 | ① 方法调用不加this. ② 方法调用不加括号(正确:this.gettableData()) ③不等于和等于:请使用双等三等 !== === |
| 静态页面 | ① 使用全局变量不在data()声明 ② 元素样式不生效:试试内联样式,优先级最高 |
| debug | ① 不命中断点: 断点之前就报错 更新代码后,新旧代码后行数不对应,要重新刷新 ② 部分页面生效: 修改了前端文件A和B,运行前端情况下,仅保存了文件A,B的修改不会生效(原因:保存只重新编译当前保存文件;解决方案:1.都保存一遍 2.停调前端重新yarn/npm run sever) |
| 不显示 | ① 未正确import(导入),或导入后未声明: ② 未设置元素宽高,默认为0 |
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- 517ttc.cn 版权所有 赣ICP备2024042791号-8
违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务