vue问题笔记

    技术2022-07-12  66

    子调父

    elementui表格里面的文字不换行,溢出隐藏,tooltip显示内容

    :show-overflow-tooltip="true"

    关于vue获取jquery $this

    <ul> <li @click="change($event)">哈哈哈</li> <li @click="change($event)">啦啦啦</li> <li @click="change($event)">嘻嘻嘻</li> </ul> methods:{ change(event){ console.log(event.currentTarget) } }

    Vue 手风琴加动画(带jqeury)

    原理:使用$(event.target)获取点击得数据 先把其他的列表隐藏 然后显示点击的列表 判断点击数据的列表是否隐藏 隐藏则把除了点击的数据之外的全部隐藏列表 把点击的数据列表打开 else显示列表 则关闭这个列表 <template> <div class="sidebar"> <div class="navigation"> <ul class="nav-wrap"> <li class="nav-item" v-for="(l,i) in lists" :key="i"> <span class="item item2" @click="toggle($event)">{{l.title}}<i class="icon_down"></i></span> <div class="nav-list"> <ul class="nav-reason"> <li v-for="(item,index) in l.items" :key="index"><a class="banner" :href="item.src" target="menuFrame">{{item.name}}</a></li> <!-- <li><a href="search.html" target="menuFrame">首页搜索</a></li> --> </ul> </div> </li> </ul> </div> </div> </template> <script> export default { name:'sidebar', data(){ return{ lists:[ { title:'我的同学', items:[{name:"张三",src:'123'}, {name:"李四",src:'456'}, {name:"王五",src:'789'}] }, { title:'我的同事', items:[{name:"张三",src:'123'}, {name:"李四",src:'456'}, {name:"王五",src:'789'}] }, { title:'我的家人', items:[{name:"张三",src:'123'}, {name:"李四",src:'456'}, {name:"王五",src:'789'}] }, ] } }, created(){ }, methods:{ toggle:function(event){ var $title = $(event.target); if($title.next().css('display') == "none"){ $title.parents('.nav-wrap').find('.nav-list').slideUp(200); $title.next().slideDown(200); }else{ $title.next().slideUp(200); } } } } </script> <style> .sidebar{ position:fixed; overflow: auto; width: 270px; height:100%; background: url('../../assets/images/sidebar_bg.gif') no-repeat; overflow: hidden; z-index: 999; } .sidebar .navigation{ width: 100%; height:92%; overflow: hidden; } .sidebar .navigation ul.nav-wrap{ position: relative; height: 100%; width: 285px; overflow:scroll; } .sidebar .navigation .nav-wrap .nav-item{ cursor:pointer; color:#fff; font-size: 22px; text-align: center; line-height: 100px; letter-spacing:8px; } .sidebar .navigation .nav-wrap .nav-item .item{ width: 104%; height: 100px; display: block; position: relative; right: 10px; } .sidebar .navigation .nav-wrap .nav-item .item2{ color:#fff; } .sidebar .navigation .nav-wrap .nav-item .item .icon_down{ position: absolute; right: 20px; width: 30px; height: 50px; /* background: url('../images/down.png') no-repeat; */ background-size:30px; text-align: left; transition:0.3s; top: -10px; transform:rotateX(180deg); } .sidebar .navigation .nav-wrap .nav-item .item .icon_down2{ transform:rotateX(0deg); top:20px; } .nav-wrap .nav-item .nav-list:nth-child(2){ width:275px; height: 100%; background: #fff; display: none; } .nav .navigation .nav-wrap .nav-item .nav-reason{ width: 100%; } .nav .navigation .nav-wrap .nav-item .nav-reason li{ width: 220px; } .nav-wrap .nav-item .nav-list .nav-reason li.active a{ color:#000; background: #f90; } .nav-wrap .nav-item .nav-list .nav-reason li a{ color:#696969; } .nav-wrap .nav-item .nav-list .nav-reason li a:hover{ color:#000; } .nav-wrap .nav-item .nav-list .nav-reason li a.active{ color:#000; } </style>

    css隐藏overflow滚轮

    ::-webkit-scrollbar { /*隐藏滚轮*/ display: none; }

    用js改变after

    原理 给div 加一个新的class ::after 新的class的after 覆盖旧的class 如 <div class="item"></div> <style> .item::after{ content:'' width:100px; height:100px } .chang::after{ content:''; width:200px; height:150px; } </style> <script> $('.item').addClass('change').parent().siblings().remover('change') </script>

    使用axios

    安装npm install vue-axios --save npm install axios --save 安装qs npm install qs.js --save  //它的作用是能把json格式的直接转成data所需的格式 安装成功后,在main.js页面引用: import Vue from 'vue' import axios from 'axios' //挂载axios import qs from 'qs' //挂在qs Vue.prototype.$axios = axios //全局注册,使用方法为:this.$axios Vue.prototype.qs = qs //全局注册,使用方法为:this.qs 基本用法 this.$axios({ method:'post', url:'api', data:this.qs.stringify({ //这里是发送给后台的数据 userId:this.userId, token:this.token, }) }).then((response) =>{ //这里使用了ES6的语法 console.log(response) //请求成功返回的数据 }).catch((error) =>{ console.log(error) //请求失败返回的数据 }) getDataInfo(){ let self = this; self.$axios({method:'get', url:'https://api.getfan.cn/activitylist/', timeout:5000,// 如果请求话费了超过 `timeout` 的时间,请求将被中断 params:{id:123456}, //传递得参数 headers: {'X-Requested-With': 'XMLHttpRequest'}, //`headers` 是即将被发送的自定义请求头 responseType: 'json', // 默认的json `responseType` 表示服务器响应的数据类型, //可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' // `validateStatus` 判断状态码 如果validateStatus返回true 将成功执行 否则 promise将被rejecte 错误 validateStatus: function (status) { return status >= 200 && status < 300; // 默认的 }, }) .then((response)=>{ console.log(response) console.log(response.data); //数据 console.log(response.status); //状态 console.log(response.statusText); // console.log(response.headers); //请求头 console.log(response.config); //全部信息 }).catch((error)=>{ if (error.response) { // 请求已发出,但服务器响应的状态码不在 2xx 范围内 console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config); }) }

    element-ui实现搜索

    思路:双向绑定搜索的内容 用watch监听数据 发生改变后调用axios获取新的数据 覆盖所有数据 如果数据为空else 调用默认获取数据方法 <el-input placeholder="请输入活动名" prefix-icon="el-icon-search" v-model="search"></el-input> <el-button type="primary" icon="el-icon-search" @click="tables()">搜索</el-button> data(){ return{ search:'' //双向绑定数据获取输入的数据 } }, watch:{ //监听数据变化 "search":function(){ let self = this; const search = self.search; //获取search数据 if(search){ self.$axios({ method:'post', url:'https://api.getfan.cn/activitylist/search/', //接口 data:{"name":search}, //post发送输入的数据 timeout:5000, }).then((response)=>{ for(var i in response.data.data.results){ // 当前时间 var timestamp = Date.parse(new Date()); // 结束时间转换时间戳 var date2 = response.data.data.results[i].deadline; date2 = date2.substring(0,19); date2 = date2.replace(/-/g,'/'); var timestamp2 = new Date(date2).getTime(); //结束时间 var date_chuo = timestamp - timestamp2 //用当前时间减去最后的结束时间 try{ //判断报名中与已结束 if(date_chuo <=0){ response.data.data.results[i].deadline = "报名中" }else{ response.data.data.results[i].deadline = "已结束" } }catch(error){ } } self.tableData = response.data.data.results //赋值数据 console.log(response.data.data.results) }).catch((error)=>{ console.log(error) }) }else{ this.$options.methods.dataInfo(self) } } }

    element-ui实现分页

    原理:获取页数 进行调用全部数据的方法 传入page页数 方法中判断page是否为真 进行更改url地址 <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize" :total="total"> </el-pagination> data(){ return{ currentPage:1, //初始页 tableData: [],//所有数据 search:'', //搜索框内容 pageSize:8,//页面可以显示的数据 total:0, url:'' } }, methods:{ handleSizeChange(size) { this.pagesize = size; // console.log(this.pagesize) //每页下拉显示数据 }, handleCurrentChange(currentPage){ this.currentPage = currentPage this.dataInfo(this,this.currentPage) //调用获取数据方法 传入第几页的值 // console.log(this.currentPage) //点击第几页 }, }

    重头戏!!!

    Vuex的作用及使用

    干啥用的! Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式;集中存储和管理应用的所有组件状态。 大白话说就是数据管理及储存 就是一个仓库 名称为 Store 总结 : Vuex就是在一个项目中,提供唯一的管理数据源的仓库。

    首先 安装

    npm install vuex --save

    然后再src文件下创建 store文件夹 然后创建index.js

    开始啦 index.js 基本内容

    import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const store = new Vuex.Store(); export default store;

    接下来,在 main.js里面引入store ,然后再全局注入一下,这样一来就可以在任何一个组件里面使用this.$store了: import store from ‘./store’//引入store

    new Vue({ el: '#app', router, store,//使用store template: '<App/>', components: { App } })

    说了上面的前奏之后,接下来就是纳入正题了,就是开篇说的state的玩法。 回到store文件的index.js里面,我们先声明一个state变量,并赋值一个空对象给它 ,里面随便定义两个初始属性值;然后再在实例化的Vuex.Store里面传入一个空对象 ,并把刚声明的变量state仍里面:

    import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const state={//要设置的全局访问的state对象 showFooter: true, changableNum:0 //要设置的初始属性值 }; const store = new Vuex.Store({ state }); export default store;

    实际上做完上面的三个步骤后,你已经可以用this. s t o r e . s t a t e . s h o w F o o t e r 或 t h i s . store.state.showFooter或this. store.state.showFooterthis.store.state.changebleNum在任何一个组件里面获取showfooter和changebleNum定义的值了,但这不是理想的获取方式;vuex官方API提供了一个getters,和vue计算属性computed一样,来实时监听state值的变化(最新状态),并把它也仍进Vuex.Store里面,具体看下面代码:

    import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const state={ //要设置的全局访问的state对象 showFooter: true, changableNum:0 //要设置的初始属性值 }; const getters = { //实时监听state值的变化(最新状态) isShow(state) { //方法名随意,主要是来承载变化的showFooter的值 return state.showFooter }, getChangedNum(){ //方法名随意,主要是用来承载变化的changableNum的值 return state.changebleNum } }; const store = new Vuex.Store({ state, getters }); export default store;

    光有定义的state的初始值,不改变它不是我们想要的需求,接下来要说的就是mutations了,mutattions也是一个对象,这个对象里面可以放改变state的初始值的方法,具体的用法就是给里面的方法传入参数state或额外的参数,然后利用vue的双向数据驱动进行值的改变,同样的定义好之后也把这个mutations扔进Vuex.Store里面,如下:

    import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const state={ //要设置的全局访问的state对象 showFooter: true, changableNum:0 //要设置的初始属性值 }; const getters = { //实时监听state值的变化(最新状态) isShow(state) { //承载变化的showFooter的值 return state.showFooter }, getChangedNum(){ //承载变化的changebleNum的值 return state.changableNum } }; const mutations = { show(state) { //自定义改变state初始值的方法,这里面的参数除了state之外还可以再传额外的参数(变量或对象); state.showFooter = true; }, hide(state) { //同上 state.showFooter = false; }, newNum(state,sum){ //同上,这里面的参数除了state之外还传了需要增加的值sum state.changableNum+=sum; } }; const store = new Vuex.Store({ state, getters, mutations }); export default store;

    这时候你完全可以用 this. s t o r e . c o m m i t ( ′ s h o w ′ ) 或 t h i s . store.commit('show') 或 this. store.commit(show)this.store.commit(‘hide’) 以及 this. s t o r e . c o m m i t ( ′ n e w N u m ′ , 6 ) 在 别 的 组 件 里 面 进 行 改 变 s h o w f o o t e r 和 c h a n g e b l e N u m 的 值 了 , 但 这 不 是 理 想 的 改 变 值 的 方 式 ; 因 为 在 V u e x 中 , m u t a t i o n s 里 面 的 方 法 都 是 同 步 事 务 , 意 思 就 是 说 : 比 如 这 里 的 一 个 t h i s . store.commit('newNum',6) 在别的组件里面进行改变showfooter和changebleNum的值了,但这不是理想的改变值的方式;因为在 Vuex 中,mutations里面的方法 都是同步事务,意思就是说:比如这里的一个this. store.commit(newNum,6)showfooterchangebleNumVuexmutationsthis.store.commit(‘newNum’,sum)方法,两个组件里用执行得到的值,每次都是一样的,这样肯定不是理想的需求

    好在vuex官方API还提供了一个actions,这个actions也是个对象变量,最大的作用就是里面的Action方法 可以包含任意异步操作,这里面的方法是用来异步触发mutations里面的方法,actions里面自定义的函数接收一个context参数和要变化的形参,context与store实例具有相同的方法和属性,所以它可以执行context.commit(’ '),然后也不要忘了把它也扔进Vuex.Store里面:

    import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const state={ //要设置的全局访问的state对象 showFooter: true, changableNum:0 //要设置的初始属性值 }; const getters = { //实时监听state值的变化(最新状态) isShow(state) { //承载变化的showFooter的值 return state.showFooter }, getChangedNum(){ //承载变化的changebleNum的值 return state.changableNum } }; const mutations = { show(state) { //自定义改变state初始值的方法,这里面的参数除了state之外还可以再传额外的参数(变量或对象); state.showFooter = true; }, hide(state) { //同上 state.showFooter = false; }, newNum(state,sum){ //同上,这里面的参数除了state之外还传了需要增加的值sum state.changableNum+=sum; } }; const actions = { hideFooter(context) { //自定义触发mutations里函数的方法,context与store 实例具有相同方法和属性 context.commit('hide'); }, showFooter(context) { //同上注释 context.commit('show'); }, getNewNum(context,num){ //同上注释,num为要变化的形参 context.commit('newNum',num) } }; const store = new Vuex.Store({ state, getters, mutations, actions }); export default store;

    而在外部组件里进行全局执行actions里面方法的时候,你只需要用执行

    this.$store.dispatch(‘hideFooter’)

    或this.$store.dispatch(‘showFooter’)

    以及this.$store.dispatch(‘getNewNum’,6) //6要变化的实参

    这样就可以全局改变改变showfooter或changebleNum的值了,如下面的组件中,需求是跳转组件页面后,根据当前所在的路由页面进行隐藏或显示页面底部的tabs选项卡

    <template> <div id="app"> <router-view/> <FooterBar v-if="isShow" /> </div> </template> <script> import FooterBar from '@/components/common/FooterBar' import config from './config/index' export default { name: 'App', components:{ FooterBar:FooterBar }, data(){ return { } }, computed:{ isShow(){ return this.$store.getters.isShow; } }, watch:{ $route(to,from){ //跳转组件页面后,监听路由参数中对应的当前页面以及上一个页面 console.log(to) if(to.name=='book'||to.name=='my'){ // to.name来获取当前所显示的页面,从而控制该显示或隐藏footerBar组件 this.$store.dispatch('showFooter') // 利用派发全局state.showFooter的值来控制 }else{ this.$store.dispatch('hideFooter') } } } } </script> }else{ this.$store.dispatch('hideFooter') } } } } </script>

    至此就可以做到一呼百应的全局响应状态改变了!

    modules 模块化 以及 组件中引入 mapGetters、mapActions 和 mapStates的使用

    因为在大多数的项目中,我们对于全局状态的管理并不仅仅一种情况的需求,有时有多方面的需求,比如写一个商城项目,你所用到的全局state可能是关于购物车这一块儿的也有可能是关于商品价格这一块儿的;像这样的情况我们就要考虑使用vuex中的 modules 模块化了,具体怎么使用modules呢?咱们继续一步一步的走:

    首先,在store文件夹下面新建一个modules文件夹,然后在modules文件里面建立需要管理状态的js文件,既然要把不同部分的状态分开管理,那就要把它们给分成独立的状态文件了,如下图:

    https://segmentfault.com/img/bVbenQd?w=355&h=278

    而对应的store文件夹下面的index.js 里面的内容就直接改写成:

    import Vue from 'vue'; import Vuex from 'vuex'; import footerStatus from './modules/footerStatus' import collection from './modules/collection' Vue.use(Vuex); export default new Vuex.Store({ modules:{ footerStatus, collection } });

    相应的js,其中的 namespaced:true 表示当你需要在别的文件里面使用( mapGetters、mapActions 接下来会说 )时,里面的方法需要注明来自哪一个模块的方法:

    //collection.js const state={ collects:[], //初始化一个colects数组 }; const getters={ renderCollects(state){ //承载变化的collects return state.collects; } }; const mutations={ pushCollects(state,items){ //如何变化collects,插入items state.collects.push(items) } }; const actions={ invokePushItems(context,item){ //触发mutations里面的pushCollects ,传入数据形参item 对应到items context.commit('pushCollects',item); } }; export default { namespaced:true,//用于在全局引用此文件里的方法时标识这一个的文件名 state, getters, mutations, actions }

    footerStatus.js

    //footerStatus.js const state={ //要设置的全局访问的state对象 showFooter: true, changableNum:0 //要设置的初始属性值 }; const getters = { //实时监听state值的变化(最新状态) isShow(state) { //承载变化的showFooter的值 return state.showFooter }, getChangedNum(){ //承载变化的changebleNum的值 return state.changableNum } }; const mutations = { show(state) { //自定义改变state初始值的方法,这里面的参数除了state之外还可以再传额外的参数(变量或对象); state.showFooter = true; }, hide(state) { //同上 state.showFooter = false; }, newNum(state,sum){ //同上,这里面的参数除了state之外还传了需要增加的值sum state.changableNum+=sum; } }; const actions = { hideFooter(context) { //自定义触发mutations里函数的方法,context与store 实例具有相同方法和属性 context.commit('hide'); }, showFooter(context) { //同上注释 context.commit('show'); }, getNewNum(context,num){ //同上注释,num为要变化的形参 context.commit('newNum',num) } }; export default { namespaced: true, //用于在全局引用此文里的方法时标识这一个的文件名 state, getters, mutations, actions }

    这样一改就有了关于两个模块的state管理文件了 footerStatus.js和collection.js,现在你要运行当前的代码话,项目会报错!因为我们把上面的代码模块化分开了,引用的地方还没有改。接下来咱们一起来看看 mapState,mapGetters,mapActions的使用,首先 在需要用的 组件里面先导入 import {mapState,mapGetters,mapActions} from ‘vuex’;咱们先修正一下隐藏或显示页面底部的tabs选项卡(就是上面举的临时例子)的组件代码

    <template> <div id="app"> <router-view/> <FooterBar v-if="isShow" /> </div> </template> <script> import {mapState,mapGetters,mapActions} from 'vuex'; //先要引入 import FooterBar from '@/components/common/FooterBar' import config from './config/index' export default { name: 'App', components:{ FooterBar:FooterBar }, data(){ return { } }, computed:{ ...mapState({ //这里的...是超引用,ES6的语法,意思是state里有多少属性值我可以在这里放多少属性值 isShow:state=>state.footerStatus.showFooter //注意这些与上面的区别就是state.footerStatus, //里面定义的showFooter是指footerStatus.js里state的showFooter }), //你也可以用下面的mapGetters来获取isShow的值,貌似下面的更简洁 /*...mapGetters('footerStatus',{ //footerStatus指的是modules文件夹下的footerStatus.js模块 isShow:'isShow' //第一个isShow是我自定义的只要对应template里v-if="isShow"就行, //第二个isShow是对应的footerStatus.js里的getters里的isShow })*/ }, watch:{ $route(to,from){ if(to.name=='book'||to.name=='my'){ this.$store.dispatch('footerStatus/showFooter') //这里改为'footerStatus/showFooter', //意思是指footerStatus.js里actions里的showFooter方法 }else{ this.$store.dispatch('footerStatus/hideFooter') //同上注释 } } } } </script>

    现在项目代码应该就不会报错了,好,最后咱们再来看一下mapActions的用法,实际上上面的this.$store.dispatch(‘footerStatus/showFooter’)已经算是一种执行相应模块的action里的方法了,但有时会牵扯的事件的触发及传值,那就会有下面的mapActions用法了,还记得上面的另一个模块collection.js吗?来看一下里面的actions中的方法结构:

    const state={ collects:[], //初始化一个colects数组 }; const getters={ renderCollects(state){ //承载变化的collects return state.collects; } }; const mutations={ pushCollects(state,items){ //如何变化collects,插入items state.collects.push(items) } }; const actions={ invokePushItems(context,item){ //触发mutations里面的pushCollects ,传入数据形参item 对应到items context.commit('pushCollects',item); } };

    需要传值来实时变动state.collects里的数据,那肯定要在执行它的地方进行传值了,所以下面用到它的地方我们用了个@click来执行这个invokePushItems方法了,并且传入相应的对象数据item,如下:

    <template> <div > <section class="joinState"> <div class="joinStateHead"> <span class="h3">全国改性料通讯录</span> <span class="joinStatus" @click="invokePushItems(item)">加入收藏列</span> </div> </section> </div> </template> <script> import { mapActions } from 'vuex' export default { components:{ conditionFilter }, name: 'bookDetail', data () { return { msg: '', item:{ id:'01', productName: '苹果', price:'1.6元/斤' } } }, mounted() { this.$store.dispatch('footerStatus/hideFooter') }, methods:{ ...mapActions('collection',[ //collection是指modules文件夹下的collection.js 'invokePushItems' //collection.js文件中的actions里的方法,在上面的@click中执行并传入实参 ]) } } </script>

    这样一来,在这个组件里面操作的 collecttion.js 中的state的数据,在其他的任何的一个组件里面都会得到相应的更新变化了,获取状态的页面代码如下:

    <template> </div> <div> <ul> <li v-for="(val,index) in arrList" :key="index"> <h5>{{val.productName}}</h5> <p>{{val.price}}</p> </li> </ul> </div> </template> <script> import {mapState,mapGetters,mapActions} from 'vuex'; export default { name: 'book', data() { return { } }, computed:{ // ...mapState({ //用mapState来获取collection.js里面的state的属性值 // arrList:state=>state.collection.collects // }), ...mapGetters('collection',{ //用mapGetters来获取collection.js里面的getters arrList:'renderCollects' }) } } </script>

    至此,vuex中的常用的一些知识点使用算是简单的完了,当然了,相信这些只是一些皮毛!

    router 路由传Id干货

    <router-link :to="{ name: 'news', params: { userId: 1111}}">click to news page</router-link> 这个通过name来传递 优点 不会暴漏id 缺点是 刷新页面id就会丢失 <router-link :to="{ path: '/news', query: { userId: 1111}}">click to news page</router-link> 这个通过path 来传递 优点 刷新页面 也不会丢失 缺点是 刷新页面id就会丢失 如何获取 在跳转得页面 用这个query 来获取 {{this.$route.query.userId}}

    跳转传参数

    方法一:this.$router.push({path:'xxx',query:{aa:xx, bb: xx}}); //带查询参数,类似于 “?” 的形式传值 方法二:this.$router.push({path:'xxx',params:{aa:xx, bb: xx}});

    Element-ui 来获取Id

    element-ui给我们封装了个方法参数 slot-scope="scope" <template class="operating" slot-scope="scope"> 方法 handleEdit 下标 这一行得数据 <el-button @click="handleEdit(scope.$index, scope.row)" type="primary" icon="el-icon-edit" circle></el-button> </template> 获取 methods:{ handleEdit(index,row){ console.log(index,row) } }

    Vue路由跳转到新页面时 默认在页面最底部 而不是最顶部 的解决

    mounted () this.$router.afterEach((to, from, next) => { window.scrollTo(0, 0) }) }

    监听路由发生变化 并且本身页面刷新数据

    $route(to,from){ var _self = this; _self.dataInfo() //重新给数组赋值 setTimeout(function(){ window.scrollTo(0, 0); },200) }
    Processed: 0.011, SQL: 9