插件
Vue插件通常为Vue添加全局功能:
1.添加全局方法或者property
2.添加全局资源,指令/过滤器/过渡等
3.添加全局混入选项
4.添加Vue实例方法
5.一个库,提供自己的API
Vue.use()接收对象或者函数,第二个参数配置参数(可选)。当是一个对象时,必须包含install方法,传入函数是把该函数当作install函数。
let myPluginObject = {}
myPluginObject.install = function (vue, options) {
console.log(vue)
console.log(options)
// 做你自己想做的...
}
let myPluginFunction = function (vue, options) {
console.log(vue)
console.log(options)
// 做你自己想做的...
}
Vue.use(myPluginObject, {
a: 1,
b: 2
})
Vue.use(myPluginFunction, {
a: 1,
b: 2
})
过滤器
Vue允许自定义过滤器,常用于文本的格式化。一般是两个地方:双花括号插值和 v-bind 表达式 (后者从 2.1.0+ 开始支持)
<!-- 在双花括号中 -->
{{ message | capitalize }}
<!-- 在 `v-bind` 中 -->
<div v-bind:id="rawId | formatId"></div>
// 全局过滤器
Vue.filter('toUpper',function(value){
console.log(value)
if (!value) return
return value.toString().charAt(0).toUpperCase() + value.slice(1)
})
let vm = new Vue({
el: document.querySelector('#id'),
data() {
return {
message: 'hello'
}
},
template: `
<div>
{{ message | toUpper }}
</div>
`
})
可以传递参数
Vue.filter('toUpper', function(data, ...args){
console.log(data) // hello
console.log(args) // [1,2,3]
})
let vm = new Vue({
el: document.querySelector('#id'),
data() {
return {
message: 'hello'
}
},
template: `
<div>
{{ message | toUpper(1,2,3) }}
</div>
`
})