定义全局变量
第一种方式:
全局变量模块文件:global.vue
Global.vue文件:
<script>
const serverSrc='www.baidu.com';
const token='12345678';
const hasEnter=false;
const userSite="中国钓鱼岛";
export default
{
userSite,//用户地址
token,//用户token身份
serverSrc,//服务器地址
hasEnter,//用户登录状态
}
</script>
接下来在text1.vue组件中使用:
<template>
<div>{{ token }}</div>
</template>
<script>
import global_ from '../../components/Global'//引用模块进来
export default {
name: 'text',
data () {
return {
token:global_.token,//将全局变量赋值到data里面,也可以直接使用global_.token
}
}
}
</script>
<style lang="scss" scoped>
</style>
第二种方式:vuex
在src下面写一个store,store里写一个index.js,在里面用state定义全局的变量
调用的时候,可以写store.state.data
定义全局函数
方法一:在main.js里面直接写函数
简单的函数可以直接在main.js里面直接写
Vue.prototype.changeData = function (){//changeData是函数名
alert('执行成功');
}
组件中调用:
this.changeData();//直接通过this运行函数
方法二:用vuex设置全局函数
在mutations下面定义方法名(一般是大写的),里面可以有两个参数,第一个为固定的,写state就行,第二个为.vue组件中传过来的参数,代码如下:
mutations:{
Login(state,data){
window.localStorage.setItem('token',data.token);
window.localStorage.setItem('userId',data.userId);
state.token=data.token;
state.userId=data.userId;
},
Logout(state){
window.localStorage.removeItem('token');
state.token=null;
// window.localStorage.removeItem('userId');
}
}
在其他页面需要调用这个函数时,直接用store.commit('方法名',{参数})
就可以
方法三:export和import
- 一个动画需要的JS库(Velocity.js)
var Velocity = function (string) {
// 这里是Velocity的具体实现算法
}
2.因为我们想在Vue组件中想要引入Velocity函数,那么要在Velocity加密算法的js脚本的最后,使用如下代码,将Velocity函数导出:
export {
Velocity
}
注:外部脚本js不要放在components文件夹下,否则会一直报错。可以在src文件夹下新建一个js文件夹,然后将外部js脚本放在这个文件夹下,然后就可以在其他Vue组件中引入该js脚本。
3.在组件中使用import { 函数名 } from 外部脚本名来从外部js脚本中导入我们需要使用的函数。
扫描二维码关注公众号,回复:
8495372 查看本文章
import { Velocity } from '../config/velocity.js'
- 在Vue组件中正常调用Velocity函数
enter: function (el, done) {
Velocity()
},
方法四:import
自定义 rem.js 文件
//px=>rem
(function (doc, win) {
var docEl = doc.documentElement,
resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
recalc = function () {
var clientWidth = docEl.clientWidth;
if (!clientWidth) return;
if (clientWidth >= 840) {
docEl.style.fontSize = '150px';
} else if (clientWidth >= 640) {
docEl.style.fontSize = '100px';
} else {
docEl.style.fontSize = 100 * (clientWidth / 640) + 'px';
}
};
if (!doc.addEventListener) return;
win.addEventListener(resizeEvt, recalc, false);
doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);
index.js(或者main,js)中引入
import '../common-vue/rem';
单个的css文件
方法1.直接在style里这么写就ok啦
@import "../static/font/iconfont.css";
方法2.@import改成引入外部样式
<style src="../static/iconfont.css"></style>
<style scoped>
</style>