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

Dev*_*iel 4 javascript vue.js vue-component vuejs2

我对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);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

我不知道我哪里出错了,尽管我尝试了文档,我仍然遇到数据如何绑定和更新的麻烦.

kmc*_*000 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);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

父组件将其标题组件向下传递给子组件,以便它可以访问它.子组件无法修改其props,因此它将prop的值复制到本地数据字段innerTitle.将input在子组件绑定到innerTitle使用V模型.添加一个手表,innerTitle以便在任何时候更改,它会发出一个事件title-changed.父组件侦听title-changed事件,无论何时发生,父组件都将其标题字段更新为该新值.

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

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