vue全套配置

本文介绍了如何在Vue项目中安装和使用Element-UI、Axios以及Qs库,详细展示了跨域配置、局部刷新、动态设置页面标题以及定时任务的实现方法。此外,还涵盖了Vue中路由的多种跳转方式和登录权限控制。通过实例展示了Vue组件的刷新技巧,以及如何在不同页面间共享和更新数据。
摘要由CSDN通过智能技术生成
安装element-ui
npm i element-ui -S
导入element-ui
  • main.js
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';


Vue.use(ElementUI);

new Vue({
  el: '#app',
  render: h => h(App)
});
安装axios
npm install --save axios
导入axios
import axios from 'axios'
Vue.prototype.axios=axios
安装qs
npm install qs
跨域config配置
  • v/config/index.js 第13行
proxyTable: {
      '/api':{
        target:'http://192.168.101.30:8000/',   
        changeOrigin:true,
        pathRewrite:{
            '^/api':''
            }
        }
    },
App.vue里的css
<style>
#app {
  /* font-family: 'Avenir', Helvetica, Arial, sans-serif; */
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  /* text-align: center;
  color: #2c3e50;
  margin-top: 60px; */
  html, body, div, h1, h2, h3, h4, h5, h6, ul, ol, dl, li, dt, dd, p, blockquote, pre, form, fieldset, table, th, td, map, figure{margin: 0; padding: 0;}
  h1,h2,h3,h4,h5,h6 { font-weight:normal;font-size:100%; }
  * html,* html body{background-attachment: fixed;}
  ul, ol, dl, li{ list-style: none;}
  pre {white-space: pre-wrap;word-wrap: break-word;}
  h1,h2,h3,h4,h5,h6{font-weight: normal;}
  h3{_zoom: 1;}
  button{font-family:微软雅黑;}
  input,textarea{resize: none; outline: none; font-family:微软雅黑;word-wrap: break-word;}
  fieldset, img{border: 0;}
  legend { display:none; }
  a{text-decoration: none;}
  a:focus{outline: none;}
  em{font-style: normal;}
  html{_overflow-x: hidden;}
  body{ background-color: #fff; font-size: 12px; font-family: 微软雅黑;}
  .clear_f{
    clear: both; overflow:hidden; height:0px;
  }
  ::-webkit-input-placeholder {/* WebKit browsers*/
      color: #bfcfed;
  }
  :-moz-placeholder{/* Mozilla Firefox 4 to 18*/
    color: #bfcfed;
  }
  ::-moz-placeholder{/* Mozilla Firefox 19+*/
    color: #bfcfed;
  }
  :-ms-input-placeholder{/* Internet Explorer 10+*/
    color: #bfcfed !important;
  }
}
</style>
post跨域
get_catalogue:function(){
            this.axios.post('/api/acquire/catalogue/',
                            Qs.stringify({  
                                question_classify:this.question_classify,
                                sex:this.sex
                            }),
                            {headers: {'X-CSRFToken': this.getCookie('csrftoken')}}
                            ).then((res)=>{
                                if(res.data.code==200){
                                    this.catalogue_list=res.data.catalogue_list
                                    this.question_count=res.data.question_count
                                    this.solve_question_count=res.data.solve_question_count
                                }else{
                                    alert('获取目录失败')
                                }
                            })
        }
        
getCookie(name) {
                var value = '; ' + document.cookie;
                var parts = value.split('; ' + name + '=');
                if (parts.length === 2) return parts.pop().split(';').shift()
            },

get跨域
get_question_classify:function(){
            this.axios.get('/api/acquire/question_classify/').then((res)=>{
                    if(res.data.code==200){
                        this.all_question_classify=res.data.res
                    }
                    }).catch(function(error){
                        console.log(error)
                    })
        },

局部刷新

在Vue中,我们经常遇到对数据进行增删改查的操作之后, 希望页面显示的是我们操作之后最新的数据, 为了避免重新做axios请求, 此时用到组件的刷新是很方便的了, 以下便是我做项目中总结的组件局部刷新的方法:

  • 首先需要修改App.vue
<template>
  <div id="app">
    <router-view v-if="isRouterAlive"/>
  </div>
</template>
<script>
export default {
  provide(){
    return{
      reload:this.reload
    }
  },
  data(){
    return{
      isRouterAlive:true
    }
  },
  methods:{
    reload(){
      this.isRouterAlive=false;
      this.$nextTick(function(){
        this.isRouterAlive=true
      })
    }
  }
}
</script>

  • 到需要刷新的页面进行引用,使用inject导入引用reload,然后直接调用即可

    ###导入
    export default{
    	inject:["reload"],
    	data(){
    		return{}
    	}
    }
    
    ###使用
    this.reload()
    
设置title
  • main.js

    Vue.directive('title', {
    	inserted: function(el) {
    		document.title = el.dataset.title
    	},
    })
    
  • 在页面最外层的div上加上以下代码

    <div class="content" v-title data-title="测试title">
    </div>
    
定时执行某请求
###循环时间为30秒
this.record_time=30
###开始将按钮变为禁用
document.getElementById('getCode').disabled=true
this.timer = window.setInterval(() => {
	setTimeout(() => {
		this.record_time=this.record_time-1			###每执行一次record_time减少1
		document.getElementById('getCode').innerText=this.record_time+'秒后再次获取'
		if(this.record_time==0){					###当record_time为0时终止循环
			document.getElementById('getCode').disabled=false
			document.getElementById('getCode').innerText='获取验证码'
			clearInterval(this.timer)
			this.timer = null
		}
	}, 0);			###0代表setTimeout不额外等待
}, 1000);			###1000代表一秒执行一次setTimeout里的请求                
路由跳转
  • router-link跳转

    1.不带参数
    <router-link :to="{name:'home'}"> 
    <router-link :to="{path:'/home'}"> //name,path都行, 建议用name 
    // 注意:router-link中链接如果是'/'开始就是从根路由开始;如果不带'/',则从当前路由开始。
     
    2.带params参数
    <router-link :to="{name:'home', params: {id:123456}}"> 
    // params传参数 (类似post)
    // 路由配置 path: "/home/:id" 或者 path: "/home:id" 
    // 不配置path ,第一次可请求,刷新页面id会消失;配置path,刷新页面id会保留。
    // html 取参 $route.params.id    script 取参 this.$route.params.id
     
    3.带query参数
    <router-link :to="{name:'home', query: {id:123456}}"> 
    // query传参数 (类似get,url后面会显示参数)
    // 路由可不配置
    // html 取参 $route.query.id    script 取参 this.$route.query.id
    
  • this.$router.push()

    1. 不带参数
    this.$router.push('/home')
    this.$router.push({name:'home'})
    this.$router.push({path:'/home'})
     
    2. query传参 
    this.$router.push({name:'home',query: {id:'123456'}})
    this.$router.push({path:'/home',query: {id:'123456'}})
    // html 取参 $route.query.id    script 取参 this.$route.query.id
     
    3. params传参
    this.$router.push({name:'home',params: {id:'123456'}}) // 只能用 name
    // 路由配置 path: "/home/:id" 或者 path: "/home:id" ,
    // 不配置path ,第一次可请求,刷新页面id会消失
    // 配置path,刷新页面id会保留
    // html 取参 $route.params.id    script 取参 this.$route.params.id
     
    4. query和params区别
    query类似get, 跳转之后页面url后面会拼接参数,类似?id=123456, 非重要性的可以这样传, 密码之类还是用params刷新页面id还在
    params类似post, 跳转之后页面url后面不会拼接参数, 但是刷新页面id会消失。
     
    
  • this.$router.replace()

    • 用法同上,和第2个的this.$router.push方法一样。
  • this.$router.go(n) :向前或者向后跳转n个页面,n可为正整数或负整数

    <button @click="upPage">[上一页]</button>
    <button @click="downPage">[下一页]</button>
    upPage() {
    this.$router.go(-1);  // 后退一步记录,等同于 history.back()
    },
    downPage() {
    this.$router.go(1);   // 在浏览器记录中前进一步,等同于 history.forward()
    }
    
ps : 区别
  • this.$router.push
    跳转到指定url路径,并向history栈中添加一个记录,点击后退会返回到上一个页面。

  • this.$router.replace
    跳转到指定url路径,但是history栈中不会有记录,点击返回会跳转到上个页面 (直接替换当前页面)。

  • this.$router.go(n)
    向前或者向后跳转n个页面,n可为正整数或负整数。

登录限制
  • v/src/main.js:进入其他页面前判断是否有缓存,如果有进入,没有登录进入/login页面

    var whittelist = ['/login']
    router.beforeEach((to, from, next) => {
      let account = window.localStorage.getItem('account');
      if (account || whittelist.indexOf(to.path) > -1) {
        next()
      }
      else {
        next('/login')
      }
    })
    
  • 登录成功时存储数据
    localStorage.setItem('account',this.account)
    
localStorage的使用
  • 获取指定key本地存储的值
    localStorage.getItem(key)
    
  • 将value存储到key字段
    localStorage.setItem(key,value)
    
  • 比如:在A页面中先存储:
    var imgs = obj_mainform.archivesId  //声明个变量存储下数据
    localStorage.setItem('key',imgs);  //将变量imgs存储到name字段
    
  • 在B页面中使用:
    var naid = localStorage.getItem("key"); //获取指定key本地存储的值
    
  • 删除
    localStorage.removeItem("名称")
    
  • 全部删除
    localStorage.clear()
    
  • 更改数据
    localStorgae.setItem('account','newdate')
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值