温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Vue中子组件访问父组件数据的方法是什么

发布时间:2022-01-24 10:28:20 来源:亿速云 阅读:170 作者:iii 栏目:开发技术

本篇内容主要讲解“Vue中子组件访问父组件数据的方法是什么”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Vue中子组件访问父组件数据的方法是什么”吧!

props

官方解释:所有的 prop 都使得其父子 prop 之间形成了一个单向下行绑定:父级 prop 的更新会向下流动到子组件中,但是反过来则不行。这样会防止从子组件意外变更父级组件的状态,从而导致你的应用的数据流向难以理解。

我们可以这样理解,当父级组件的数据发生改变的时候,子级组件接受的数据也会自动发生改变,但子级组件改变的数据不能对父级数据进行影响这也就是单向下行绑定。

但子组件不能直接引用父组件中的数据。我们需要进行引用。

子组件对父组件的数据引用

我们以两个 vue 界面为例

父组件为 HomeComponent,子组件为 TopArticles。

HomeComponent.vue

<script>
export default {
  name: "HomeComponents",
  components: {TopCoders, TopArticles, ComingCompetitions, TopNews},
  data() {
    return {
      topArticle:[
        {
          title:'title1',
          url:'url1',
          author:'author1'
        },
          {
          title:'title2',
          url:'url2',
          author:'author2'
        }
      ],
    }
  }
}
</script>

HomeComponent 在引用子组件的时候需要向子组件传递绑定数据。即 :top-articles=“topArticle”

HomeComponent.vue

<template>
  <div >
        <top-articles class="articles" :top-articles="topArticle"></top-articles>
  </div>
</template>

data 中的 topArticle 为 topArticle 界面中需要引用的父级组件的数据。

指定数据的类型

topArticles.vue

<script>
export default {
  name: "topArticle",
  props: {
    topArticles: {
      // 指定类型
      Type: Array,
      required: true
    },
  },
}
</script>

数据展示

topArticles.vue

<template>
  <div>
    <sui-list>
      <sui-list-item v-for="(item, key) in topArticles">
        <span >{{item.title}}</span>
        <span >{{item.author}}</span>
      </sui-list-item>
    </sui-list>
  </div>
</template>

效果展示

Vue中子组件访问父组件数据的方法是什么

到此,相信大家对“Vue中子组件访问父组件数据的方法是什么”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue
AI