常用代码摘要【自用】

35 阅读3分钟

git分支删除

git push origin --delete name # 删除远程分支stark
git branch -D name      # 强制删除本地stark分支
git fetch --prune      # 刷新远程分支列表

npm清除缓存

npm cache clean --force
npm install

路由守卫

export default {
    beforeRouteEnter(to, from, next) {
    	next(vm => {
            if (to.name && PageCacheConfig[to.name]) {
                if (vm.pageCacheList.includes(to.name)) {
                    // no
                } else {
                    to.meta.keepAlive = true;
                    vm.addPageCache(to.name);
                }
            }
        });
    },
    beforeRouteLeave(to, from, next) {
        // 当前路由配置了路由名以及缓存配置中配置了该路由才进行相关操作
        if (from.name && PageCacheConfig[from.name]) {
            if (PageCacheConfig[from.name].includes(to.path)) {
                // 配置中包含前往路径,则缓存,否则不缓存
                from.meta.keepAlive = true;
                if (this.pageCacheList.includes(from.name)) {
                    // no
                } else {
                    this.addPageCache(from.name);
                }
            } else {
                from.meta.keepAlive = false;
                this.deletePageCache(from.name);
            }
        }
        next();
    }
};

iframe-html跨域通信

addEventListener第一个参数:  事件名。 addEventListener第二个参数:  指定事件触发时候执行的函数。 addEventListener第三个参数:  true事件句柄在捕获阶段执行。 false事件句柄在冒泡阶段执行。

/* myVue.vue */
    
<template>
	<div>
        <iframe id="iframe" :src="iframeUrl" name="iframe"/>
        <button @click='handlePostMessage'>向html发送数据</button>
    </div>
</template>

<script>
	export default{
        data(){
            return {
                iframeUrl: 'www.baidu.com'
            }
        },
        mounted(){
            this.init()
        },
        methods:{
            init(){
                /* 接收html页面传递过来的message参数 */
                window.addEventListener('message', event => {
                    console.log(event.data.code)
                }, false)
            },
            handlePostMessage(){
                const myframe = document.getElementById('iframe')
                myframe.contentWindow.postMessage({ msg: '我是一个传递的参数' }, '*')
            }
        }
    }
</script>

<style lang='less' scoped>
</style>
<!-- iframe嵌入的html页面 -->
<html>
    <head>
        <title>html页面</title>
    </head>
    <body>
        <div>Hello World!</div>
        <button @click='handlePostMessage'>向vue发送数据</button>
        
        <script>
        	window.onload = function(){
                window.addEventListener('message', function(e){
                    console.log(e.data.msg) /* 输出: 我是一个传递的参数 */
                })
            }
            function handlePostMessage(){
                window.parent.postMessage({ code: 'this is a code!' }, '*')
                /* window.parent.postMessage(JSON.stringify({ code: 'this is a code!' }), '*') */
            }
        </script>
    </body>
</html>

父页面与子页面参数互调

方法1
<!-- 父页面 -->
<template>
	<div>
        <son :message='message' @childrenParams='handleGetChildrenMessage'/>
    </div>
</template>

<script>
  import son from './son.vue'
	export default{
        data(){
            return {
                message:'我是父页面的参数'
            }
        },
        mounted(){},
        methods:{
            handleGetChildrenMessage(msg){
                console.log(msg)
            }
        }
    }
</script>

<style lang='less' scoped>
</style>
<!-- 子页面 -->
<template>
	<div>{{ message }}</div>
	<button @click='handlePostMessage'>向父页面传递参数</button>
</template>

<script>
	export default{
        prop:{
            message: String
        },
        data(){
            return {}
        },
        mounted(){},
        methods:{
            handlePostMessage(){
                this.$emit('childrenParams', '我是子页面的参数!')
            }
        }
    }
</script>

<style lang='less' scoped>
</style>
方法2
this.$parent  /* ====> 可以获取父页面的data(), methods:{}中的属性和方法 */
this.$children  /* ====> 可以获取子页面的data(), methods:{}中的属性和方法 */
方法3
/* 当变量较多时,用于存储参数列表 */
const params = {
    message: '我是参数Bus!'
}
export default params
/* 子页面与父页面可以同时调取文件中的参数并操作 */
<template>
	<div />
</template>

<script>
    import bus from './bus'
	export default{
        watch:{
            'bus.message':function(){
                console.log(bus.message)
            }
        }
    }
</script>

<style lang='less' scoped>
</style>
方法4
<son ref="children"><son>
 
export default {
  mounted: {
    let son = this.$refs.children
  }
}

路由哈希控制

<template>
	<div>
        <!-- 当点击更多时,在路由上添加 #ChooseVillage -->
        <!--<img v-if="show" src='www.baidu.com/bg/1.png'>-->
        
        <span @click="$router.push({ hash: 'ChooseVillage' })">更多</span>
        <img v-if="$route.hash==='baidu'" src='www.baidu.com/bg/1.png'>
    </div>
</template>

<script>
	export default{
        data(){
            return {
                /*show: false*/
            }
        },
        watch: {
            '$route.hash' (value) {
      		this.show = value === '#baidu'
            }
        },
    }
</script>

根据接口文档快速生成文档脚本

表格

let param = document.querySelectorAll('#param tr')
let notes = ' * @param {Object} [params]'
for (dom of param) {
    let td = dom.querySelectorAll('td')
    let file = td[0].innerText
    let type = td[1].innerText
    let notBlank = td[2].innerText === '否'
    let desc = td[3].innerText
    notes += `\n * @param { ${type} } ${notBlank?'[params.': 'params.'}${file} ${notBlank?'] 非必填':'必填'} ${desc}`
}
console.log(notes)

swagger

const trs = document.querySelectorAll('#ele tr')
let notes = ' * @param {Object} [params]'
for (let i=0;i<trs.length;i++) {
	const left = trs[i].querySelectorAll('.parameters-col_name')?.[0]
	const right = trs[i].querySelectorAll('.parameters-col_description')?.[0]
	const name = left.querySelectorAll('.parameter__name')?.[0]?.innerText
	const type = left.querySelectorAll('.parameter__type')?.[0]?.innerText || 'String'
	const label = right.querySelectorAll('.markdown p')?.[0]?.innerText || '其他'
    notes += `\n * @param { ${type} } params.${name} ${label}`
}
console.log(notes)

超出隐藏...

.rowLine{
  display: inline-block;//设置行内块属性
  white-space: nowrap; //强制不换行
  width: 100%; //固定盒子的宽度
  overflow: hidden;//超出部分隐藏
  text-overflow:ellipsis;//显示‘...’
  cursor: pointer;
  color: dodgerblue;
}
.lines{
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

判断多元素节点超出隐藏状态

<templete>
  <div v-for="item in data" :key="item.id">
    <!-- 初始化节点,用于判断元素高度 -->
    <div class="hidden">{{ item.desc }}</div>
    <!-- 当前元素没有超出,不显示... -->
    <div v-if="!toolCache[`ref_${item.id}`]">{{ item.desc }}</div>
    <!-- 当前元素超出,显示... -->
    <el-tooltip v-else :content="item.desc" >
      <div class="title-desction">{{ item.desc }}</div>
      <template v-slot="content">
        <div class="max-width">{{ item.desc }}</div>
      </template>
    </el-tooltip>
  </div>
</templete>

<script setup>
  import { ref } from 'vue'
  import { getData } from '@/service'
  
  const data = ref([]) // 数据
  const toolCache = ref({}) // 是否超出隐藏缓存
  const loadData = async ()=>{
    const res = await getData()
		data.value = res.content || []
    nextTick(() => {
			const refNames = data.value.map(o => `ref_${o.id}`)
			refNames.forEach(refName => {
				nextTick(() => {
					var scrollHeight = proxy.$refs[refName]?.[0]?.scrollHeight
					var offsetHeight = proxy.$refs[refName]?.[0]?.offsetHeight
					toolCache.value[refName] = offsetHeight < scrollHeight
				})
			})
		})
  }
</script>

<style>
  /* 设置显示不在屏幕显示范围 */
  .hidden{
    position: absolute;
		top: -9999px;
  }
  /* tooltip设置最大显示宽度 */
  .max-width{
    max-width: 300px;
  }
  /* 超出显示... */
  .title-desction{
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
</style>

flex一行显示,展示滚动条

.page-container {
    display: flex;
    width: 100%;
    overflow-x: auto;
    .card-item {
        display: inline-block;
        margin-right: 12px;
        flex-shrink: 0;
        &:last-child {
            margin-right: 0;
        }
    }
}

element formRule

rlue:{
    againDelayDays: [
      { required: true, message: '重新报备延期不能为空' },
      { type: 'number', message: '格式错误(单位: 天)' },
      {
        validator: (rule, value, callback) => {
          if (!value) {
            return callback(new Error('报备保护期不能为空'))
          }
          if (value > 999 || value < 0) {
            return callback(new Error('请输入1-999(单位: 天)'))
          }
        }
      }
    ]
}

vue多文件组件化使用

<templete>
  <component :is="name" />
</templete>

<script setup>
  import AAA from './AAA.vue'
  import BBB from './BBB.vue'
  import CCC from './CCC.vue'

  const componentsMap = {
      AAA: 'AAAComponentName', // AAA组件的name
      BBB: 'BBBComponentName', // BBB组件的name
      CCC: 'CCCComponentName', // CCC组件的name
  }
  let key = AAA
  const name = componentsMap[key]
</script>

窗口切换

document.addEventListener("visibilitychange", function() {
  if(document.visibilityState == 'hidden'){
    document.title = '瞅啥呢,快回来!!';
    setTimeout(function(){
      document.title = '要走终究留不住,祝安好~~';
    }, 1500);
  }else{
    document.title = '这就对了~~';
  }
});

promise用例

<button @click=“okClick”>按钮</button>
<div style="display: show?'block':'none'">
  <button @click=“confirm”>确认</button>
  <button @click=“cancel”>取消</button>
</div>

<script>
  let show = false
  let confirm = ()=>{}
  let cancel = ()=>{}

  const okClick = ()=>{
    show = true
    // 在这里没有使用reject,因为在调用页面获取当前返回值,也可以直接抛出错误
    return new Promise((resolve, reject)=>{
      confirm = () => {
        show = false
      	resolve("confirm")
      }
      cancel = () => {
        show = false
      	resolve("cancel")
      }
    })
  }
</script>