Vue:从Vue实例更新组件数据

时间:2017-11-14 09:14:17

标签: vue.js vuejs2

我想从我的Vue实例更新组件中的数据。找到关于如何做相反事情的大量例子,但没有任何内容。

说我有:

Vue.component('component', {
props: {
    prop: {
        default: null
    }
},
template: '#template',
data: function () {
    return {
        open: false
    };
}
});

现在我想从我的Vue实例中将open设置为true

var root = new Vue({
    el: '#root',
    data: {},
    methods: { updateComponentData: function() {//set open to true} } });

2 个答案:

答案 0 :(得分:10)

您应该能够使用Child Component Ref

<div id="category" class="ui fluid search selection dropdown" [class.error]="formErrors.category">
    <input name="category" type="hidden" formControlName="category">
    <i class="dropdown icon"></i>
    <div class="default text">Select Category...</div>
    <div class="menu">
        <div class="item" *ngFor="let item of categories" data-value="item._id">{{item.name}}</div>
  </div>
</div>
<script type="text/x-template" id="template" ref="component">
    <div>Hello, {{ name }}!</div>
</script>

工作示例

&#13;
&#13;
var root = new Vue({
  el: '#root',
  data: {},
  methods: { 
    updateComponentData: function() {
      this.$refs.component.open = true
    } 
  } 
});
&#13;
const Child = Vue.component('child', {
  template: `
    <div>
      <h2>Component1</h2>
      <div>Hello, {{ title }}! <strong>{{ open }}<strong></div>
    </div>
  `,
  data() {
    return {
      title: 'component',
      open: false
    }
  }
});

var root = new Vue({
  el: '#app',
  components: {
    Child
  },
  methods: { 
    updateComponentData: function() {
      //console.log('updateComponentData', this.$refs)
      this.$refs.component1.open = true
    } 
  } 
});
&#13;
&#13;
&#13;

答案 1 :(得分:1)

我刚刚使用了您的代码,以下代码工作正常,请尝试一下。我使用了Vue&#39; ref&#39;。在组件中添加ref属性,然后您可以从父级访问特定组件数据。

&#13;
&#13;
Vue.component('component', {
    props: {
        prop: {
            default: null
        }
    },
    template: '#template',
    data: () => ({
        open: false
    })
});
var root = new Vue({
    el: '#root',
    data: () => ({}),
    methods: {
        updateComponentData: function() {
			      this.$refs.myComponent.open = true
        }
    },
});
&#13;
<script src="https://unpkg.com/vue"></script>
<div id="root">
	  <button @click="updateComponentData">Change</button>
    <hr>
    <component ref='myComponent'></component>
</div>
<script type="text/x-template" id="template" ref="component">
    <div>Open: {{ open }}!</div>
</script>
&#13;
&#13;
&#13;