vue常用功能

前言

之前第一次做项目遇到的一些功能, 可能看起来小白, 但是我删减了很多更小白的功能了, 过段时间来看这些功能, 再增加删减。

目录

获取当前时间(vue2.0)

禁止鼠标右键和阻止后退的所有菜单

随机颜色函数

路由跳转传值

localStorage存值和取值

vuex的存值和取值

简易版多图一起轮播

模糊查询

自动搜索


获取当前时间(vue2.0)

getTime: function () {
      var _this = this;
      let yy = new Date().getFullYear();
      var mm =
        new Date().getMonth() < 10
          ? "0" + (new Date().getMonth() + 1)
          : new Date().getMonth() + 1;
      var dd =
        new Date().getDate() < 10
          ? "0" + new Date().getDate()
          : new Date().getDate();
      let hh = new Date().getHours();
      let mf =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      let ss =
        new Date().getSeconds() < 10
          ? "0" + new Date().getSeconds()
          : new Date().getSeconds();
      _this.gettime = yy + "-" + mm + "-" + dd + " " + hh + ":" + mf + ":" + ss;
      console.log( _this.gettime)
},

禁止鼠标右键和阻止后退的所有菜单

created() {
    this.stopF5Refresh();
},

stopF5Refresh() {
      document.onkeydown = function(e) {
        var evt = window.event || e;
        var code = evt.keyCode || evt.which;
        //屏蔽F1---F12
        if (code > 111 && code < 124) {
          if (evt.preventDefault) {
            evt.preventDefault();
          } else {
            evt.keyCode = 0;
            evt.returnValue = false;
          }
        }
      };

      //禁止鼠标右键菜单
      document.oncontextmenu = function(e) {
        return false;
      };

      //阻止后退的所有动作,包括 键盘、鼠标手势等产生的后退动作。
      history.pushState(null, null, window.location.href);
      window.addEventListener("popstate", function() {
        history.pushState(null, null, window.location.href);
      });
}

随机颜色函数

function getRandom(){
    var allType="0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f";
    var allTypeArr=allType.split(",");
    var color="#";
    for(var i = 0; i < 6; i++){
        var random = parseInt(Math.random() * allTypeArr.length);
        color += allTypeArr[random];
        console.log(color);
    }
    return color;
}

路由跳转传值

1. router-link

使用query传递参数,路由必须使用path引入; 使用params传递参数,路由必须使用name引入。

<router-link :to="{path:'/test',query: {userid: id}}">
    跳转
</router-link>

2. $router 

取值方式 this.$route.query.name(params一样),页面刷新的时候, query传的值不会消失,但params传值会消失。

this.$router.path({
  path: '/detail',
  query: {
    name: 'admin',
    code: 10021
  }
})

url拼接路由的取值方式 this.$route.params.id

this.$router.push({
    path: `/approveManage/approveDetail/${item.id}`
})

localStorage存值和取值

var userID = null;
// 存值方法
localStorage.setItem('storeID',JSON.stringify(userID));
localStorage["name"]="bonly";
localStorage.name="bonly";

// 取值方法
this.userID = JSON.parse(localStorage.getItem(storeID));
this.userID = JSON.parse(localStorage["name"]);
this.userID = JSON.parse(localStorage.name);

// 移除某个值的方法
localStorage.removeItem("name");
delete localStorage["name"];
delete localStorage.name;

// 获取所有的值
localStorage.valueOf();

// 清除所有的值
localStorage.clear();

// 获取所有key
for (var i=0;i<localStorage.length;i++) {
	console.log(localStorage.key(i));
}
for(var key in localStorage){
	console.log(key);
}

//判断是否具有某个key
localStorage.hasOwnProperty("name")
// 如果存在的话返回true,不存在返回false

注意事项

  1. localStorage特定于页面的协议,不是同一域名,不能访问。
  2. 有长度限制,5M左右,不同浏览器大小会有不同。
  3. 生命周期是永久的,但是数据实际是存在浏览器的文件夹下,可能卸载浏览器就会删除。
  4. 浏览器可以设置是否可以访问数据,如果设置不允许会访问失败。
  5. 兼容IE8以上浏览器
  6. 只能存储字符串类型,需要转成字符串存储。

使用技巧

  1. 先判断浏览器是否支持localStorage,通过if(!window.localStorage) return;
  2. 单词太长,不方便书写,可以利用 var storage=window.localStorage;
  3. 字符串和原始类型需要通过JSON.stringfy转字符串,通过JSON.parse转成对象
  4. 通过封装方法实现来回转化

vuex的存值和取值

在scr目录下创建一个vuex文件夹, 将store.js放到store目录下。

store.js 中:

import Vuex from 'vuex'
import Vue  from 'vue'

Vue.use(Vuex)

export default new Vuex.Store({
    state:{ id: '' },
    mutations:{
        setId(state,id) {
            state.id = id            
        }
    }
}) 

传递方法:

A界面改变store中state里的参数:

  1. 可以通过直接赋值的方法进行改变 this.$store.state.id = (要传递的参数id)
  2. 官方建议的修改方法: this.$store.commit( 'setId' ,(要传递的参数id) )

B界面接收变化数据参数:this.$store.state.id

但是通过 vuex这样写,页面刷新之后,数据也会消失。它只是对变量提升。

简易版多图一起轮播

<div id="bottom_multis" v-on:mouseover="stopmove()" v-on:mouseout="move()">
    <!-- 左边箭头 -->
    <p class="jint" @click="leftMove()" style="float: left; margin-right: 20px">
      <img src="../static/img/xiazaiy.svg" alt="" />
    </p>
    <div class="lunhover">
      <ul class="lunboul" :style="{ left: curleft + 'vw' }">
        <!-- 每次展示多张图片 -->
        <li v-for="(imgitem,index) in imglist" :key="index">
          <span> <img :src="imgitem.src" alt="" /></span>
          <p class="img_title">
            {{ imgitem.content }}
          </p>
        </li>
      </ul>
    </div>
    <!-- 右边箭头 -->
    <p class="jint" @click="rightMove()" style="float: right">
      <img src="../static/img/xiazaiz.svg" alt="" />
    </p>
</div>

export default {
  data: () => ({
    imglist: [
      {
        content: "1212",
        src: "../static/img/upar1_0.jpg",
      },
      {
        content: "1313",
        src: "../static/img/upar1_7.jpg",
      },
      {
        content: "1414",
        src: "../static/img/upar1_8.jpg",
      },//下一组展示图片
      {
        content: "4545",
        src: "../static/img/upar1_0.jpg",
      },
      {
        content: "4646",
        src: "../static/img/upar1_1.jpg",
      },
      {
        content: "4747",
        src: "../static/img/upar1_2.jpg",
      },
    ],
    curleft: 0,
    timer: null,
  }),
  created() {
    this.move();
  },
  methods: {
    // 定时器
    move() { this.timer = setInterval(this.startmove, 5000)},
    // 开始移动
    startmove() {
      this.curleft -= 14.1;
      if (this.curleft <= -85) {
        this.curleft = 0;
      }
    },
    // 暂停
    stopmove() {clearInterval(this.timer)},
    // 点击左边箭头
    leftMove() {
      this.curleft -= 14.1;
      if (this.curleft <= -85) {
        this.curleft = 0;
      }
    },
    // 点击右边箭头
    rightMove() {
      this.curleft += 14.1;
      if (this.curleft > 0) {
        this.curleft = -85;
      }
    },
  }, 
}

<style lang="scss">
#bottom_multis { 
  .lunhover {
    position: absolute;
    height: 140px;
    width: 85vw;
    left: 116px;
    overflow: hidden;
    white-space: nowrap;
  }
  .lunboul {
    position: absolute;
    height: 140px;
    width: 10000px;
    left: 0px;
  }
  ul > li {
    width: 13vw;
    height: 140px;
    float: left;
    margin-right: 19px;
    span {
      display: inline-block;
      border: 1px solid #ccc;
      width: 12.9vw;
      height: 114px;
    }
    img {
      width: 96%;
      height: 94%;
      margin: 3px;
    }
    .img_title {
      font-size: 13px;
      text-align: center;
      padding: 0 16px;
      overflow: hidden;
      text-overflow: ellipsis; /*超出隐藏显示...*/
      white-space: nowrap;
    }
    .img_title:hover {
      color: rgb(70, 128, 194);
      text-decoration: underline;
    }
  }
  .jint {
    width: 30px;
    height: 140px;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .jint:hover {
    background: #e3eef5;
  }
}
</style>

模糊查询

<input class="conteninp" type="text" placeholder="请输入搜索内容" v-model.trim="searchValue" />
<button @click="search()">高级检索</button>
<div class="xiala" v-show="xialaShow">
    <ul>
        <li>下拉</li>
        <li
        @click="xialaClick(abcitem.index, abcitem.content)"
        v-for="abcitem in abc"
        :key="abcitem.index"
        >{{ abcitem.content }}</li>
    </ul>
</div>

export default {
   data: () => ({
   		searchValue: "",
   		searchIndex: null,
   		xialaShow: false,   // 下拉显示
   		abc: [],
   		list: [
          { index: 0, content: "西南河流源区河流水系数据" },
          { index: 1, content: "西南河流源区监测站点分布数据" },
          { index: 2, content: "中国气象要素数据降水小时观测资料" },
          { index: 3, content: "黄河源区水资源量年际数据" },
          { index: 4, content: "黄河源区各省份产业经济数据" },
          { index: 5, content: "黄河源区各省份土地利用类型数据" },
          { index: 6, content: "青藏高原湖泊数据集" }
        ],
   }),
   // 监听值是否有变化
   watch: {
    searchValue(val, oldVal) {
      if (val != oldVal) {
        // 过滤出词汇
        this.abc = this.list.filter(function(product) {
          return Object.keys(product).some(function(key) {
            return (
              String(product[key]).toLowerCase().indexOf(val) > -1
            );
          });
        });
      } else if (val.length === 0) {
        this.abc = this.list;
      }
      this.xialaShow = true;
    }
  },
   methods: { 
    // 点击li标签
    xialaClick(index, value) {
      this.searchIndex = index;
      this.searchValue = value; 
      this.xialaShow = false;
    }, 
  },
}

自动搜索

<template>
  <div id="top_multis">
    <div class="top_searchinp">
      <input class="conteninp" type="text" placeholder="搜一搜" v-model.trim="searchValue" />
      <button @click="btnSearch()">高级检索</button>
    </div>
  </div>
</template>
<script>
// 节流函数
const dalay = (function(){
  let timer = 0;
  return function(callback, ms){
    clearTimeout(timer);
    timer=setTimeout(callback, ms)
  }
})();
export default {
  data: () => ({searchValue:"",}),
  methods: {
    async fetchData(val){
      if ($(".conteninp").val() == "好") {
        this.$router.push({ path: "/topsear" });
      }
    }
  },
  watch:{
    // 监听页面变量的改变
    searchValue(){
      dalay(()=>{
        this.fetchData();
      }, 800)
    }
  }
};
</script>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

molanyouming

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值