// 注册一个全局自定义指令 `v-focus`
Vue.directive('focus',{
当被绑定的元素插入到 DOM 中时……
inserted: function (el) {
聚焦元素
el.focus()
}
})
directives: {
focus: {
指令的定义
inserted: (el) {
el.focus()
}
}
}
div id="hook-arguments-example" v-demo:foo.a.b="message"></div>
Vue.directive('demo' (el,binding,vnode) {
var s = JSON.stringify
el.innerHTML =
'name: ' + s(binding.name) + '<br>' +
'value: ' + s(binding.value) + '<br>' +
'expression: ' + s(binding.expression) + '<br>' +
'argument: ' + s(binding.arg) + '<br>' +
'modifiers: ' + s(binding.modifiers) + '<br>' +
'vnode keys: ' + Object.keys(vnode).join(',')
}
})
new Vue({
el: '#hook-arguments-example'
}
})
name: "demo"
value: "hello!"
expression: "message"
argument: "foo"
modifiers: {"a":true,"b":true}
vnode keys: tag,data,children,text,elm,ns,context,fnContext,fnOptions,fnScopeId,key,componentOptions,componentInstance,parent,raw,isStatic,isRootInsert,isComment,isCloned,isOnce,asyncFactory,asyncMeta,isAsyncPlaceholder
Vue.directive('color-swatch', binding.value
})
v-demo="{ color: 'white',text: 'hello!' }">
Vue.directive('demo',binding) {
console.log(binding.value.color) => "white"
console.log(binding.value.text) => "hello!"
})
MyPlugin.install = (Vue,options) {
1. 添加全局方法或属性
Vue.myGlobalMethod = () {
逻辑...
}
2. 添加全局资源
Vue.directive('my-directive' }
...
})
3. 注入组件
Vue.mixin({
created: () {
4. 添加实例方法
Vue.prototype.$myMethod = (methodOptions) {
}
}
调用 `MyPlugin.install(Vue)`
Vue.use(MyPlugin)
Vue.use(MyPlugin,{ someOption: true })
用 Browserify 或 webpack 提供的 CommonJS 模块环境时
var Vue = require('vue')
var VueRouter = require('vue-router')
不要忘了调用此方法
Vue.use(VueRouter)
template>
>封装一个最简单的插件</>
script>
export default{
name:'count-down
}
>
import countDown from './countdown';
countDown.install = (Vue){
Vue.component(countDown.name,countDown)
};
export default countDown;
import countDown from './components/countdown/index.js'
Vue.use(countDown)
定义一个混合对象
var myMixin = {
created: this.hello()
},methods: {
hello: () {
console.log('hello from mixin!')
}
}
}
定义一个使用混合对象的组件
var Component = Vue.extend({
mixins: [myMixin]
})
var component = new Component() => "hello from mixin!"
var mixin = () {
console.log('混合对象的钩子被调用')
}
}
Vue({
mixins: [mixin],created: () {
console.log('组件钩子被调用' => "混合对象的钩子被调用"
// => "组件钩子被调用"
{
methods: {
foo: () {
console.log('foo')
},conflicting: () {
console.log('from mixin'var vm = () {
console.log('bar' () {
console.log('from self')
}
}
})
vm.foo() => "foo"
vm.bar() => "bar"
vm.conflicting() => "from self"
为自定义的选项 'myOption' 注入一个处理器。
Vue.mixin({
created: var myOption = .$options.myOption
if (myOption) {
console.log(myOption)
}
}
})
Vue({
myOption: 'hello!'
})
=> "hello!"
Vue.config.optionMergeStrategies.myOption = (toVal,fromVal) {
return mergedVal
}
var strategies = Vue.config.optionMergeStrategies
strategies.myOption = strategies.methods