vuejs2 - 如何从VueJS中的组件获取数据

标签 vuejs2 components

我有以下组件:

组件

<template>
<div>
  <label class="typo__label">Single selecter</label>
  <multiselect v-model="value" :options="options" :searchable="false" :close-on-select="false" :show-labels="false" placeholder="Pick a value"></multiselect>
</div>
</template>

<script>
import Multiselect from 'vue-multiselect'

export default {
  components: {
    Multiselect
  },
  data () {
    return {
      value: '',
      options: ['Select option', 'options', 'selected', 'mulitple', 'label', 'searchable', 'clearOnSelect', 'hideSelected', 'maxHeight', 'allowEmpty', 'showLabels', 'onChange', 'touched']
    }
  }
}
</script>

我在我的页面中使用它,如下所示:
<p id="app-two">
  <dropdown></dropdown>
  @{{ value }}
  @{{ message }}
</p>

<script>
    new Vue({
    el: '#app',
    data: {
        message: 'Test message'
    }
});
</script>

当我运行页面时,@{{ message }} 显示“测试消息”但@{{ value }} 为空白。
我可以看到下拉组件的值在 VueJS Dev Tools 中得到更新,但它没有显示在页面上。如何访问我的 vue 元素中的组件数据?类似@{{ dropdown.value }}

最佳答案

<template>
    <div>
      <label class="typo__label">Single selecter</label>
      <multiselect v-model="internalValue" :options="options" :searchable="false" :close-on-select="false" :show-labels="false" placeholder="Pick a value">  </multiselect>
    </div>
</template>

<script>
    import Multiselect from 'vue-multiselect'

    export default {
      components: {
        Multiselect
      },
      props: ['value'],
      data () {
        return {
          internalValue: this.value,
          options: ['Select option', 'options', 'selected', 'mulitple', 'label', 'searchable', 'clearOnSelect', 'hideSelected', 'maxHeight', 'allowEmpty', 'showLabels', 'onChange', 'touched']
        }
      },
      watch:{
         internalValue(v){
             this.$emit('input', v);
         }
      }
    }
</script>

并在您的页面中
<p id="app-two">
  <dropdown v-model="selectedValue"></dropdown>
  @{{ selectedValue}}
  @{{ message }}
</p>

<script>
    new Vue({
    el: '#app',
    data: {
        selectedValue: null
        message: 'Test message'
    }
});
</script>

Here is an example ,不使用多选,而是实现对 v-model 支持的自定义组件.

关于vuejs2 - 如何从VueJS中的组件获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42684754/

相关文章:

javascript - 通过字符串名称访问 Vue 组件的方法

vue.js - 在 v-if 中使用方法函数

Angular Cli-在 StyleURL 中添加位于 node_module 目录中的 css 文件

c++ - 如何使用模板继承和组件

components - 格式化程序在尝试反序列化消息 : There was an error while trying to deserialize parameter 时抛出异常

Laravel @stack 在组件中

angular - 如何在 Angular 2 中将事件从深层嵌套的子级传递给父级?

vuejs2 - nuxtjs 中的 vuex 模块模式

javascript - VueJS : How to pass props while redirecting

javascript - Json 数组对象访问