javascript - 怎样写这个指令,让它看起来像是一个整体?

查看:66
本文介绍了javascript - 怎样写这个指令,让它看起来像是一个整体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

<div id="EmailInput" v-dir-email.needat="emailAddress">
    <input type="text" v-model="emailAddress">
    <ul>
        <li v-for="email in emails | filterBy host" @click="setEmail(email)">{{email}}</li>
    </ul>
</div>

Vue.directive('DirEmail',{
    bind:function(){},
    update:function(newValue){
        if(!newValue) return;
        var needAt=this.modifiers.needat || false,
            emails=[],
            at=newValue.indexOf('@'),
            user='';
        if(needAt && !~at){
            this.vm.emails=emails;
            return false;
        }
        if(~at){
            this.vm.host=newValue.substr(at);
            user=newValue.substr(0,at);
        }
        else{
            this.vm.host='';
            user=newValue;
        }
        for(var n in hosts){
            emails.push(user+'@'+hosts[n]);
        }
        this.vm.emails=emails;
    },
    unbind:function(){}
})

var hosts=['126.com','163.com','qq.com','yahoo.com','yahoo.com.cn'];
new Vue({
    el:"#EmailInput",
    data:function(){
        return {
            emailAddress:'',
            host:'',
            emails:[]
        }
    }
})

现在指令跟实例是分开的,但是逻辑上,它们应该是一个整体才对,应该怎么写才能把它们两个整合到一起呢?是把指令里边的东西,写在实例里边还是怎么样呢?

我把实例中的data移动到directive里边,刷新没问题,往里一打值就报错。我在bind钩子上使用this.vm.$set也是报错,都报

Vue warn: You are setting a non-existent path "emailAddress" on a vm instance. Consider pre-initializing the property with the "data" option for more reliable reactivity and better performance.

好像是说无法在实例上设置不存在的数据。


我找到方法了,是在directive的bind中使用Vue.set(),把属性设置进去。但是为什么不能用this.vm.$set,教程里边明明写着可以用这两种方法,但是使用后者总报上边那个错(设置不存在的路径错误)。

解决方案

實際上如果你要建立一個 全局 的指令的話,就只能這樣做,可以放在實例裡面,但就不是全局了,而是當前實例底下才有作用,例如你放在 Component 底下,那就只有該 Component 底下才能用。

这篇关于javascript - 怎样写这个指令,让它看起来像是一个整体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆