简体   繁体   English

Vue.js自定义指令不运行componentUpdated钩子?

[英]Vue.js custom directive doesn't run componentUpdated hook?

So when I load the code below the bind hook triggers just fine, however the componentUpdated hook never seems to run despite the class of the component it is bound to changing from "neutral" to "include". 因此,当我加载下面的代码时, bind hook触发就好了,但是尽管组件的类必须从“中性”更改为“包含”,但componentUpdated挂钩似乎永远不会运行。 Can someone help me determine why the update is never run even when an instance of the component with the attached directive is clicked? 有人可以帮我确定为什么即使单击带有附加指令的组件实例,也永远不会运行更新?

HTML HTML

<ternary-toggle display-text="Broken" v-ternary="'baz'"></th>

JS JS

Vue.directive('ternary', {
    bind: function(el, binding) {

        var instanceName = JSON.stringify(binding.value);
        if (this['_' + instanceName] == undefined) {
            this['_' + instanceName] = {};
        }
    },
    componentUpdated: function(el, binding) {
        var instanceName = JSON.stringify(binding.value);
        console.log(instanceName);
    }
});

var ternaryToggle = Vue.component('ternary-toggle', {
    props: ['displayText'],
    data: function() {
        return {
            state: 'neutral',
            stateTransitions: {
                neutral: 'include',
                include: 'exclude',
                exclude: 'neutral'
            }
        }
    },
    methods: {
        toggle: function() {
            this.state = this.stateTransitions[this.state]
            this.$emit('switched', this.state)
        }
    },
    template: '<span v-bind:class="state + \' btn btn-small\'" v-on:click="toggle">{{ displayText }}</span>'
});

This doesn't quite properly answer the question (can't recall why this solution worked) but it's an attempt to help @Jeppebm. 这不能很好地回答这个问题(不记得为什么这个解决方案有效)但是它试图帮助@Jeppebm。 So I can't recall the precise reason why but the following was what I ended up with: 所以我不记得确切的原因,但以下是我最终的结果:

var ternaryToggle = Vue.component('ternary-toggle', {
    props: ['displayText', 'toggleId'],
    data: function() {
        return {
            state: 'neutral',
            stateTransitions: {
                neutral: 'include',
                include: 'exclude',
                exclude: 'neutral'
            }
        }
    },
    methods: {
        toggle: function() {
            this.state = this.stateTransitions[this.state]
            this.$emit('switched', this.toggleId, this.state)
        }
    },
    template: '<span v-bind:class="state + \' btn btn-small\'" v-on:click="toggle">{{ displayText }}</span>'
});

I think the overall conclusion I came to might have been to just ditch the custom directive for this effort. 我认为我得出的总体结论可能就是放弃了这项工作的自定义指令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM