在项目开发中,模块化是非常好的工程实践。可以极大的提高组件的复用性和项目的可维护性。本文介绍在 Vue 中使用 ES6 的模块功能实现封装业务逻辑。
在 ES6 以前,前端就可以使用Require.js或者Sea.js实现模块化,Require.JS是基于AMD规范的模块化库,而像Sea.js是基于CMD规范的模块化库。现在ES6自带了模块化,也是javascript语音标准中第一次支持模块。
在 ES6 中,使用单文件单模块的方法,在一个文件中定义的常量,变量,函数,对象等一切,在默认情况下都是被现在在局部(文件内)的,对于文件外部都不可见的,除非用 Export 显式的声明为外部可见。
在Vue中,我们可以使用模块将业务功能从 vue 文件中剥离出来,提高复用性和可为维护性。
Export
下面使用 使用 vue-router 进行页面导航 中构建的案例来模拟这个做法,如果对于在 vue 中进行页面导航的知识还不熟悉,请先参考该文。
在案例的跟目录新建一个名为 biz 的目录,再 biz 目录中新建一个名为 common.js 的文件。
在 common.js 中定义一个产生随机数的函数, 如下:
1 2 3
| let getRandom = function() { return Math.random(); }
|
现在这个 getRandom 函数只能在 common.js 文件中被访问,要想在外部访问,必须 export 它,代码如下:
Import
我们在 Splash.vue 中使用这个函数,首先需要 import,
1
| import {getRandom} from '../biz/common.js'
|
然后在Vue 对象的 methods 属性中定义一个方法映射:
这一步主要是规避 ESLint 的 no-unused-vars 规则,否则会报错。
最后直接在模版中绑定函数即可:
1
| <h1>Splash: {{random()}}</h1>
|
Splash.vue 完整的代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <template> <div> <h1>Splash: {{random()}}</h1> <button v-on:click="goHome">Go to Home</button> <div> <router-link v-bind:to="{ name: 'home', params: {clickAd: false}}">Link to Home</router-link> </div> </div> </template>
<script> import {getRandom} from '../biz/common.js'
export default { name: 'splash', methods: { goHome: function() { this.$router.push({ name: 'home', params: {clickAd: false}}) }, random: getRandom } } </script>
<style>
</style>
|
处理 export 函数,也可以 export 对象和变量。
封装对后台Rest服务的访问
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| import axios from 'axios'
const BASE_URL = "<your server address and port>" const AUTH_TOKEN_KEY = "<your token key>"
const instance = axios.create({ baseURL: BASE_URL, headers: {'content-type': 'application/json'} })
var token = ''
const SecAccessor = { login: function(path, body, sucess, fail) { instance.post(path , body , {}) .then((result) => { if (result.data.succ) { token = result.data.data this.saveToken() sucess(result.data.data) } else { fail(result.data.code, result.data.msg) } }, (error) => { console.error(error) }) }, access: function(path, body, sucess, fail) { if (token === '' || token == null) { this.pickToken() } instance.post(path, body, {headers: {AUTH_TOKEN_KEY: this.token}}) .then((result) => { if (result.data.succ) { sucess(result.data.data) } else { fail(result.data.code, result.data.msg) } }, (error) => { console.error(error) }) }, saveToken: function() { localStorage.setItem(AUTH_TOKEN_KEY, token) }, pickToken: function() { token = localStorage.getItem(AUTH_TOKEN_KEY) }, removeToken: function() { localStorage.removeItem(AUTH_TOKEN_KEY) }, isLogin: function() { this.pickToken() if ( token === '' || token == null ) { return false } else { return true } }
}
export default SecAccessor
|