我有一个指令,我想在指令中创建一个本地方法,并在钩子函数中使用它。下面是我的代码:
export const OutsideClick = {
bind (el, binding, vnode) {
console.log(new Vue());
// call method1()
},
componentUpdated(el, binding, vnode) {
console.log('updated comp', binding);
if(binding.value[1]()) {
// call method1();
}
},
unbind(el, binding, vnode) {
console.log('unbinding');
}
}那么现在如何在指令中定义函数并在bind和componentUpdated中使用它呢?
发布于 2019-03-14 16:17:02
我不认为你可以在指令中添加一个方法。但是您可以在指令外部声明该方法,并从内部调用它。
function method1 (el, binding, vnode) {
...
}
export const OutsideClick = {
bind (el, binding, vnode) {
console.log(new Vue());
method1(el, binding, vnode)
},
componentUpdated(el, binding, vnode)
{
console.log('updated comp', binding);
if(binding.value[1]()) {
method1(el, binding, vnode)
}
},
unbind(el, binding, vnode) {
console.log('unbinding')
method1(el, binding, vnode)
}
}发布于 2019-03-14 16:21:29
那么,您需要在指令之外添加函数,并按照下面的示例在生命周期方法中调用它。
Vue.directive("color", {
"bind": function() {
console.log("directive active");
hello();
},
"unbind": function() {
console.log("directive deactive");
},
"update": function(newValue, oldValue) {
var el = $(this.el);
if (this.arg == 'background')
el.css('background', newValue);
else
el.css('color', newValue);
},
});
function hello() {
console.log('hello');
}
new Vue({
el: '#app'
});<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.24/vue.min.js"></script>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<div id="app">
<h2>Color</h2>
<select v-model="color">
<option value="#f00">Red</option>
<option value="#0f0">Green</option>
<option value="#00f">Blue</option>
<option value="#000" selected>Black</option>
</select>
<br><br>
<div v-color="color">
Hello world!!!
</div>
<h2>Background</h2>
<select v-model="color2">
<option value="#f00">Red</option>
<option value="#0f0">Green</option>
<option value="#00f">Blue</option>
<option value="#000" selected>Black</option>
</select>
<br><br>
<div v-color:background="color2">
Hello world!!!
</div>
</div>
发布于 2021-07-06 17:52:02
也许有人会发现它很有帮助。诀窍是用构造函数包装一个指令。
function myDirective() {
this.myMethod = function() {
console.log('My method')
}
return {
bind: function(el) {
el.addEventListener('click', this.myMethod)
}.bind(this),
update: function() {
this.myMethod()
}.bind(this),
unbind: function(el) {
el.removeEventListener('click', this.method)
}.bind()
}
}
Vue.directive('myDirective', new myDirective())
new Vue({
el: '#app'
});<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button v-my-directive>Just a button</button>
</div>
此外,还可以用lambdas () => {}替换带有.bind(this)的函数。
https://stackoverflow.com/questions/55157157
复制相似问题