Vue.js 2,从指令更改数据

Kei*_*owe 6 javascript directive properties vue.js vue-component

使用单个文件组件,如何从指令更改数据属性?

所以,例如,我有......

export default {
    name: 'app',
    data: function() {
        return {
            is_loading: true
        }
    },
    directives: {
        do_something: {
            bind: function(el, binding, vnode) {
                // Change the is_loading property
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

起初,我以为我可以做this.is_loading = false,但是thisundefined.

cra*_*g_h 13

this在指令中引用,您可以简单地使用vnode.context,因此在您的指令中,您将拥有:

    do_something: {
        bind: function(el, binding, vnode) {
            // same as this.is_loading in a directive
            vnode.context.is_loading = false;
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后在你的标记中你会做:

<div v-do_domething></div>
Run Code Online (Sandbox Code Playgroud)

这是JSFiddle:https://jsfiddle.net/3qvtdgyd/

  • 文档说将除“el”以外的所有内容都视为只读。https://vuejs.org/v2/guide/custom-directive.html 还有另一种方法吗? (3认同)