本文介绍下vue模块化下全局过滤器的用法,以及Object.keys;map();forEach();
还有vue中export和export default和import写法的区别
src/filters/index.js
exports.datefmt = (input) => { var res = ""; var date = new Date(input); var year = input.getFullYear(); var month = input.getMonth() + 1; var day = input.getDate(); var date = year + "-" + month + "-" + day; console.log(date); return date;}
main.js
import filters from './filters';Object.keys(filters).forEach(k => Vue.filter(k, filters[k]));
hello.vue
{ {item.ctime | datefmt}}
然后再介绍一下vue2.0的filters的传参写法
index.jsconst datefmt = function(input,format){ var res = ""; var date = new Date(input); var year = input.getFullYear(); var month = input.getMonth() + 1; var day = input.getDate(); if(format == 'yyys-mm-dd'){ var date = year + "-" + month + "-" + day; }else{ var date = year + "-" + month + "-" + day + " 14:25:33"; } console.log(format); return date;}export default {datefmt};hello.vue { {item.ctime | datefmt('yyys-mm-dd')}}
意思便为vue里面过滤器自定义传参一个字符串,然后通过过滤器里面看是不是相同的字符串来匹配规则
下来这边扫盲一下Object.keys;map();forEach();
方法会返回一个由一个给定对象的自身可枚举属性组成的数组。
map与foreach参数基本一样,但是返回值foreach为underfind,map为数组具体参考https://www.cnblogs.com/chenzhiyu/p/8692845.htmlvar obj = {'a':'123','b':'345'};console.log(Object.keys(obj)); //['a','b']//把这个map替换成forEach,里面打印的结果一模一样Object.keys(obj).map((currentValue, index,arr)=>{ console.log(currentValue,index,arr); //currentValue=>当前元素的值(必须) index=>当前元素的索引值 arr=>当前元素属于的数组对象 // a 0 (2) ["a", "b"] //b 1 (2) ["a", "b"]});Object.keys(filters).forEach(key => { console.log(key);//datefmt console.log(filters);//{datefmt: ƒ}所以filters[key]便为datefmt过滤器定义的方法 Vue.filter(key, filters[key])})
emp:官方文档的全局过滤器定义为以下:
为Vue.filter(key, filters[key])以上:
Vue.filter('capitalize', function (value) { if (!value) return '' value = value.toString() return value.charAt(0).toUpperCase() + value.slice(1)})
export和export default
这里只简单介绍下vue中用法的区别,详细的请查看阮一峰ES6
export的用法:
比如上面说的index.js里面写
index.jsvar firstName = 'Michael';var lastName = 'Jackson';var year = 1958;export {firstName, lastName, year};main.jsimport {firstName, lastName, year} from './filters';console.log(firstName, lastName, year)//Michael Jackson 1958
export default的用法:
index.jsvar firstName = 'Michael';var lastName = 'Jackson';var year = 1958;export default {firstName, lastName, year};main.jsimport filters from './filters';console.log(filters)//{firstName: "Michael", lastName: "Jackson", year: 1958}
可以看出两者最重要的区别在于import引用后export default这里是可以通过别名的,而export必须通过对象的引进才能有值