【问题标题】:How to bind components with vue js?vue js如何绑定组件?
【发布时间】:2018-05-25 09:32:50
【问题描述】:

我有表单和选择组件。 其实事情很简单:我需要两个绑定模型。

父组件:

    Vue.component('some-form', {
      template: '#some-form',
      data: function() {
        return {
          countryNameParent: ''
        }
      }
   });

带有项目的子组件:

Vue.component('countries', {
  template: '#countries',
  data: function () {
    return {
      items: {
        "0": {
          "id": 3,
          "name": "Afghanistan"          
        },
        "1": {
          "id": 4,
          "name": "Afghanistan2"          
        },
        "2": {
          "id": 5,
          "name": "Afghanistan3"          
        }
      },
      countryName: ''
    }
  },
  props: ['countryNameParent'],
  created: function() {
    var that = this;
    this.countryName = this.countryNameParent;
  },

  methods: {
    onChange: function (e) {
      this.countryNameParent = this.countryName;
    }
  }
});

我正在使用v-model 来合并上面的组件。 像这样的模板:

<template id="some-form">
  {{ countryNameParent }}
  <countries v-model="countryNameParent"></countries>
</template>

<template id="countries">
  <label for="">
    <select name="name" @change="onChange" v-model="countryName" id="">
      <option value="0">Select the country!</option>
      <option v-for="item in items" v-bind:value="item.name">{{ item.name }}</option>
    </select>
  </label>
</template>

我的目标是在父组件中获取数据以将其发送到服务器(实际形式要大得多),但是我无法获得countryNameParentcountryName 的值。此外,Parent 不为空时,应在后继设置数据。

给你link,我一直在尝试以多种方式做到这一点(请参阅其中的评论部分)。 我知道我需要使用$emit 来正确设置数据,我什至实现了将图像作为base64 以相同形式发送的模型,因此我认为解决方案即将到来!

另外:reference 我用图像构建了示例。

【问题讨论】:

  • 你只需要正确实现v-model。这是你的pen updated
  • 我很感激!谢谢!

标签: javascript vue.js vuejs2


【解决方案1】:

这是您的 countries 组件更新以支持 v-model

Vue.component('countries', {
  template: `
  <label for="">
    <select v-model="countryName">
      <option value="0">Select the country!</option>
      <option v-for="item in items" v-bind:value="item.name">{{ item.name }}</option>
    </select>
  </label>
  `,
  data: function () {
    return {
      items: {
        "0": {
          "id": 3,
          "name": "Afghanistan"          
        },
        "1": {
          "id": 4,
          "name": "Afghanistan2"          
        },
        "2": {
          "id": 5,
          "name": "Afghanistan3"          
        }
      },
    }
  },
  props: ['value'],
  computed:{
    countryName: {
      get() { return this.value },
      set(v) { this.$emit("input", v) }
    }
  },
});

v-model 只是设置value 属性和监听input 事件的糖。所以要在任何组件中支持它,组件需要接受value 属性,并发出input 事件。使用哪个属性和事件是可配置的(记录在here)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-17
    • 2017-07-08
    • 1970-01-01
    • 2018-07-03
    • 2017-08-21
    • 2020-10-14
    • 1970-01-01
    • 2017-05-24
    相关资源
    最近更新 更多