【问题标题】:Vue2 use $ref to load data from child component and put into parent component's dataVue2 使用 $ref 从子组件加载数据并放入父组件的数据
【发布时间】:2022-01-16 20:18:19
【问题描述】:

在 Vue2 中,我试图访问子组件的数据,然后在不触发事件的情况下放入父组件的数据。在下面的例子中,我想把 count:20 保存到父组件中,如果有错误请告诉我,谢谢!

子组件

<template>
  <div></div>
</template> 
<script>
export default {
  data() {
    return {
      count: 20,
    };
  },
};
</script>

父组件

<template>
  <div>
    <child ref="child1"></child>
    {{count}}
</div>
</template> 

<script> import child from './child.vue' 
export default { 
  components: {
    child
  }, 
  data() {
    return{
      count:this.$refs.child1.count
    }
  },
} 
</script>

VScode 中的警告信息

“Vue | 类型”上不存在属性“count”元素 | Vue[] |元素[]'。 类型“Vue”上不存在属性“count”。

浏览器中的警告消息

[Vue 警告]:data() 中的错误:“TypeError: undefined is not an object (evalating 'this.$refs.child1')”

【问题讨论】:

    标签: vue.js components vue-component ref


    【解决方案1】:

    首先,我建议按预期使用 Vue 框架。所以将数据从子节点传递给父节点应该使用$emit 或使用 vuex 存储进行集中状态管理。

    这样一来,您将需要等到安装父组件才能设置 count 数据属性。

    儿童

    <template>
      <div></div>
    </template> 
    <script>
    export default {
      data() {
        return {
          count: 20,
        };
      },
    };
    </script>
    

    家长

    <template>
      <div>
        <child ref="child1"></child>
        {{ count }}
      </div>
    </template>
    
    <script>
    import Child from "./components/Child";
    
    export default {
      components: {
        Child
      },
      data() {
        return{
          count: 0
        }
      },
      mounted () {
        this.count = this.$refs.child1.count
      }
    };
    </script>
    

    这会起作用,但它不会是被动的。这一切都可以大大简化,并通过以下更改做出反应:

    儿童

    <template>
      <div></div>
    </template> 
    <script>
    export default {
      data() {
        return {
          count: 20,
        };
      },
      watch: {
        count (currentValue) {
          this.$emit('update', currentValue);
        }
      },
      beforeMount () {
        this.$emit('update', this.count)
      }
    };
    </script>
    

    家长

    <template>
      <div>
        <child @update="count = $event"></child>
        {{ count }}
      </div>
    </template>
    
    <script>
    import Child from "./components/Child";
    
    export default {
      components: {
        Child
      },
      data() {
        return{
          count: 0
        }
      }
    };
    </script>
    

    显示工作示例的快速链接:https://codesandbox.io/s/interesting-kalam-et0b3?file=/src/App.vue

    【讨论】:

    • 非常感谢,mounted () 有效!我听说过 emit 但我不确定它是否必须由事件触发。在这种情况下,我需要加载几个子组件并对它们的一个属性求和而不做任何事情,这就是我尝试使用 $ref 的原因。无论如何,感谢您的解决方案,您真的让我很开心!
    猜你喜欢
    • 2018-12-07
    • 2017-06-13
    • 1970-01-01
    • 2018-03-06
    • 2016-09-05
    • 1970-01-01
    • 2020-04-14
    • 2017-10-01
    • 2021-04-23
    相关资源
    最近更新 更多