我想从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} } });

推荐答案

你应该能用Child Component Ref分做到.

<script type="text/x-template" id="template" ref="component">
    <div>Hello, {{ name }}!</div>
</script>
var root = new Vue({
  el: '#root',
  data: {},
  methods: { 
    updateComponentData: function() {
      this.$refs.component.open = true
    } 
  } 
});

Working example

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
    } 
  } 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>

<div id="app">
  <h2>Parent</h2>
  <button v-on:click="updateComponentData">Click me true</button>
  <child ref="component1"></child>
</div>

Vue.js相关问答推荐

Vue路由路径匹配行为

Vue3:如何在功能组件中重用插槽vnode

写入计算值时出错,但我没有写入任何值

是否可以使用 Vuetify/VueJS 为轮播设置默认图像而不是第一个图像?

如何在 vue2.7 中删除 slot-scope

如何在Vue js 3中根据API响应替换react 值

Vue3 动态渲染

CssSyntaxError 使用 Webpack 4 构建未知单词

如何在vue中动态加载组件

使用 Laravel 作为后端刷新 Vue.js SPA 的身份验证令牌

如何对对象数组进行 v-model

aspnet core如何在deploy上构建webpack

使用 Vue 和 JS 下载 CSV 文件

Bootstrap-vue b-table,标题中带有过滤器

在没有组件的vue js中拖放

v-for 如何在继续之前判断未定义的列表

VS代码中的红点是什么意思

在Vue中单击路由链接上的激活方法

使用 Vuetify 的可滚动数据表

如何在 vue3 中的setup方法中发出事件?