使用Vue开发网站之路2-多组件通信2(利用Vuex进行数据传递)

这里还是非父子组件间的通信

其实我也不喜欢看别人的大段代码,但这是最完整的,以后肯定有用(完整代码贴在最后面,自己看)

主要实现是使用vuex的公共空间存放数据,这个时候要问,那为什么不之间用一个对象啊,其他也是可以的,但是vuex可以检测你数据的变化,这个后期有用。

继续,

主要实现是新建一个Vuex.Store,然后在mutations里面编写你要修改数据的方法。再在在要修改数据的组件里使用store.commit("setName",value);,最好不要直接赋值,为了可以检测你的数据变化,vue本来就数据驱动的框架。另一个组件想要获取数据的话直接store.state.userName这么一下就可以了。

题外话:(其实vuex我现在还用的不够多,因为要实现的功能简单。也就先用用,后面肯定会继续深入的。其实有时候觉得会用一个框架真的没什么了不起的,真正厉害的是知道它为什么这么涉及,怎么设计的,如果是我的话,用现有的知识能不能做出一样的效果。就像java为什么只有单继承,大学里老师可没教,也就是后面看设计模式的时候才知道,哦,原来是为了实现组合。)

    //使用vuex在不关联组件之间进行通信
    const store = new Vuex.Store({
        state:{
            userName:""
        },
        mutations:{
            setName(state,name) {
                state.userName = name;
            }
        }
    })
    //密码
    Vue.component("user-password",{
        props:["value"],
        template:'
password:\ \
', data:function() { return { placeholder:ls.enterPassword } }, methods:{ targetClick:function(e) { var target = $(e.target); target.removeClass("is_empty"); }, updateValue:function(target) { this.$emit("input",target.value); var target = $(target); target.removeClass("is_empty"); }, savePassword:function(value) { store.commit("setName",value); } } }); //再次密码 Vue.component("user-password-again",{ props:["value"], template:'
password:\ \ \
', data:function() { return { placeholder:ls.enterPasswordAgain, checkResult:"" } }, methods:{ targetClick:function(e) { var target = $(e.target); target.removeClass("is_empty"); }, updateValue:function(target) { this.$emit("input",target.value); var target = $(target); target.removeClass("is_empty"); }, //失去焦点后检验两个密码是否相等 checkPassword:function(value) { if(value == store.state.userName) { this.checkResult = "两次结果相同"; } } } });



你可能感兴趣的:(vue)