VueJS v模型和组件之间的数据绑定

时间:2017-12-27 14:01:37

标签: javascript vue.js vuejs2 vue-component

我遇到了vuejs如何绑定数据的麻烦。我有一个父Vue.component,它是处理我的表单的布局,我有子vue.component处理不同的输入组。当我将来提交表单时,我很难将子组件中的数据与父组件同步。

我目前的文件是这样的:

var title = "";
Vue.component('create_new_entry', {
    template: '<div><div class="row"><h1 v-on:click="test()">{{title}}</h1><div class="col-md-12"><section_title></section_title></div></div></div>',
    data    : function() {
        return {
            title: title
        };
    },
});
Vue.component('section_title', {
    template: '<div><h1 v-on:click="test()">{{title}}</h1><input type="text" class="form-control" v-model="title"></div>',
    data    : function() {
        return {
            title: title
        };
    },
    methods : {
        test: function() {
            console.log(this);
        }
    }
});

我不确定我哪里出错了,并且我尝试使用文档时仍然遇到数据如何绑定和更新的问题。

1 个答案:

答案 0 :(得分:6)

您正在声明两个完全独立的字段,每个组件中有一个字段,并且除了它们共享相同的名称之外没有任何东西将它们绑在一起。 Vue将这些视为两个独立的字段,当一个变化时,另一个不变。这些字段是私有的,并且是组件实例的内部字段。

共享状态应该作为props传递给子组件,并且应该作为事件传递给父组件。有几种方法可以解决这个问题,最简单的方法是添加道具和事件。更复杂的方法是使用像vuex这样的状态管理工具。 https://github.com/vuejs/vuex

以下是使用道具和事件的简单示例。

道具文件:https://vuejs.org/v2/guide/components.html#Props

活动文档:https://vuejs.org/v2/guide/components.html#Custom-Events

var title = "";
Vue.component('create_new_entry', {
    template: '<div><div class="row"><h1 v-on:click="test()">{{title}}</h1><div class="col-md-12"><section_title :title="title" @title-changed="changeTitle"></section_title></div></div></div>',
    data    : function() {
        return {
            title: title
        };
    },
    methods: {
        changeTitle(newTitle) {
            this.title = newTitle;
        }
    }
});
Vue.component('section_title', {
    template: '<div><h1 v-on:click="test()">{{title}}</h1><input type="text" class="form-control" v-model="innerTitle"></div>',
    props: ['title'],
    data    : function() {
        return {
            innerTitle: this.title
        };
    },
    methods : {
        test: function() {
            console.log(this);
        }
    },
    watch: {
        title(val){
            this.innerTitle = val;
        },
        innerTitle(val) {
            this.$emit('title-changed', val);
        }
    }
});

父组件将其标题组件向下传递给子组件,以便它可以访问它。子组件无法修改其props,因此它将prop的值复制到本地数据字段innerTitle。子组件中的input使用v-model绑定到innerTitleinnerTitle上添加了一个手表,因此只要它发生变化,它就会发出一个事件title-changed。父组件侦听title-changed事件,无论何时发生,父组件都将其标题字段更新为该新值。

子组件还在title道具上有一个监视器,这样如果父级的标题值因任何其他原因而改变,子组件将能够更新其内部状态以匹配父级的新值。 / p>

如前所述,您也可以使用Vuex,或使用其他Vue实例作为总线,如此处所述https://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication

相关问题