vue2 笔记本项目

173 阅读3分钟

1、var/let/const

image.png

image.png

2、解构赋值

image.png

image.png

function add([x,y]=[1,2]){
  return x + y
}

image.png

image.png

1.字符串

image.png

2、数组 image.png

image.png

3、函数

image.png

image.png

箭头函数

没有参数和有两个及以上参数时必须要加圆括号; image.png

image.png

对象

image.png

模块化

image.png

image.png

image.png

image.png

类和继承

image.png

image.png

image.png

yarn 报错 unlink

把所有服务停掉,再下载包,否则一直 unlink!!!

webstorm 报错

使用Eslint检验项目报错“Component name “Error“ should always be multi-word“解决办法

编辑 .eslintrc.js

module.exports = {
  ……
  overrides: [
    {
      files: ['src/views/**/*.vue'],
      rules: {
        'vue/multi-word-component-names': 0,
      },
    },
  ]
}

image.png

image.png

跨域请求携带 cookie

f15a59ae091e62fd46ffb9dabb721db.png

import axios from 'axios'
import baseURLConfig from './config-baseURL'
import {Message} from 'element-ui'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.baseURL = baseURLConfig.baseURL
axios.defaults.withCredentials = true

chrome在2020年3月份升级了安全策略,对于跨域请求如果想写入cookie,必须是https的网站才可以。对于http的网站,cookie写入总是失败。

解决方案:

第一步 修改build/webpack.dev.conf 文件,在devServer里添加https: true, 如下图

image.png

image.png

第二步

执行 npm start, 浏览器输入 https://localhost:8080 。注意是https, 不是 http
此时并不能打开页面,而是显示如下

image.png

image.png

解决:就是在当前页面用键盘输入 thisisunsafe ,不是在地址栏输入,就直接敲键盘就行了,页面即会自动刷新进入网页。
因为Chrome不信任这些自签名ssl证书,为了安全起见,直接禁止访问了,thisisunsafe 这个命令,说明你已经了解并确认这是个不安全的网站,你仍要访问就给你访问了。

第三步
代码里使用接口时都需要指明使用https的接口,比如 https://note-server.hunger-valley.com/***

用浏览器测试接口

1、写好接口文件

import request from '../helpers/request'

const URL = {
  GET:'/notebooks',
  ADD:'/notebooks',
  UPDATE:'/notebooks/:id',
  DELETE:'/notebooks/:id'
}

export default {
  getAll(){
    return request(URL.GET)
  },
  updateNotebook(notebookId,{title=''}={title:''}){
    return request(URL.UPDATE.replace(':id',notebookId),'PATCH',{title})
  },
  deleteNotebook(notebookId){
    return request(URL.DELETE.replace(':id',notebookId),'DELETE')
  },
  addNotebook({title=''}={title:''}){
    return request(URL.ADD,'POST',{title})
  }
}

2、引用接口文件,将接口方法放到 window 上,作为全局方法使用

<script>
import Notebooks from '../apis/notebook'
window.Notebooks = Notebooks

</script>

3、在当前项目,打开浏览器,测试接口

Notebooks.addNotebook({title:'hihihi'}).then(res=>{console.log(res)})

处理时间戳

export function friendlyDate(datsStr){
  let dateObj = typeof datsStr === 'object' ? datsStr : new Date(datsStr)  
  //new Date("2022-04-20T08:30:16.948Z").getTime()
  //得到1650443416948
  let time = dateObj.getTime()
  let now = Date.now()
  let timeOver = now - time
  let str
  let sec = 1000*60  //1分钟
  switch (true){
    case timeOver < sec:
      str = '刚刚'
      break;
    case timeOver < sec*60:
      str = Math.floor(timeOver/sec)+'分钟前'
      break;
    case timeOver < sec*60*24:
      str = Math.floor(timeOver/(sec*60))+'小时前'
      break;
    default:
      str = Math.floor(timeOver/(sec*60*24))+'天前'
  }
  return str
}

# npm start 报错npm ERR! code ELIFECYCLE

安装 elementui 后,npm start报错 image.png 原因:导入新项目缺少依赖;
解决方案:
Step1:npm cache clean --force
Step2:rm -rf node_modules
Step3:rm -rf package-lock.json
Step4:npm install
重新 npm start

route

使用 /note:id,用$route.params.id获取 id 值
使用/note?id=xxx时,用$route.query.id获取 id 值。

使用 markdown-it 处理 markdown 格式内容

npm install markdown-it

import MarkdownIt from "markdown-it"
let md = MarkdownIt()

computed: {
  previewContent() {
    return md.render(this.currentNote.content || '')
  },
}

//将 markdown 内容变为 html 格式
<div class="preview markdown-body" v-html="previewContent" v-show="isShowPreview"></div>

less 的 cacl 属性

需要加 ~"", 而且-两边要有空格;

height:~"calc(100% - 71px)";

路由懒加载和别名

别名:将 / 别名为 /notebooks,意味着当用户访问 /notebooks 时,URL 仍然是 /notebooks,但会被匹配为用户正在访问 /

懒加载:当路由被访问的时候才加载对应组件,这样就会更加高效。

localhost:8080/#/note?noteId=7761&notebookId=6116 :

/note : /后面是 params ;

?noteId=7761&notebookId=6116 :? 后面是 query

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      alias:'/notebooks',
      component: ()=>import('../components/NotebookList.vue')
    }
  ]
})

static 目录

项目打包为 dist 之后,文件中的引用路径会发生改变,而 static 中的资源,在打包时不会改变,直接复制到 dist/static 目录下,所以这个目录会放一些不希望被一起打包的东西。

引入 css 文件

1、有引号

@import '//at.alicdn.com/t/font_3355909_67ypb809vsi.css';

2、没有引号

@import url(../assets/css/trash-detail);

使用 axios

import axios from 'axios'
import baseURLConfig from './config-baseURL'
import {Message} from 'element-ui'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.baseURL = baseURLConfig.baseURL
//服务端设置好 cors 后,可以跨域,可以请求到数据,但是再次发送请求时无法带上 cookie ,要进行以下设置,当 axios 发请求时会带上 cookie :
axios.defaults.withCredentials = true

export default function request(url, type = 'GET', data = {}) {
  return new Promise((resolve, reject) => {
    let option = {
      url,
      method: type,
      validateStatus(status) {
        return (status >=200 && status < 300) || status === 400
      }
    }
    if(type.toLowerCase() === 'get') {
      option.params = data
    }else {
      option.data = data
    }
    axios(option).then(res => {
      if(res.status === 200) {
        resolve(res.data)
      }else {
        Message.error(res.data.msg)
        reject(res.data)
      }
    }).catch(err=>{
      Message.error(err)
      reject({msg: '网络异常'})
    })
  })
}