vue父组件向子组件传值

背景

vue要进行数据交互,若父组件要向子组件传值要怎么办那

方法

父组件的标签引用时,添加v-bind,子组件的props接收注册

父组件App.vue

<template>
  <div id="app">
    <users v-bind:users="users"></users>   //v-bind传值
  </div>
</template>

<script>
  import Users from './components/Users'

  export default {

    data(){
      return {
        users:[
        {name:"beiqiu",position:"web开发",show:false},
        {name:"beiqiu",position:"web开发",show:false},
        {name:"beiqiu",position:"web开发",show:false},
        {name:"beiqiu",position:"web开发",show:false},
        {name:"beiqiu",position:"web开发",show:false},
        {name:"beiqiu",position:"web开发",show:false},
        {name:"beiqiu",position:"web开发",show:false},
        {name:"beiqiu",position:"web开发",show:false},
        {name:"beiqiu",position:"web开发",show:false}
        
        ]
      }
    },

    components:{
      "users":Users

    }
  }

</script>

<style scoped>
  h1{
    color:red;
  }
</style>

子组件Users.vue

<template>
  <div class="users">
    <h1>hello users</h1>
    <ul>
      <li v-for="user in users" v-on:click="user.show=!user.show">
        <h2>{{user.name}}</h2>
        <h3 v-show="user.show">{{user.position}}</h3>
      </li>
    </ul>
  </div>

</template>
<script>
  export default{
    name:"users",        //props注册
    // props:["users"],  这是简易方式
    props:{              //这是官方方式
      users:{
        type:Array,      //类型
        required:true    //是否规范
      }
    },
    data(){
      return{
        
      }
    }
  }
</script>

<style scoped>
  .users{
    width:100%;
    max-width:1200px;
    margin:40px auto;
    padding:0 20px;
    box-sizing:border-box;

  }

  ul{
    display:flex;
    flex-wrap:wrap;
    list-style-type:none;
    padding:0px;;
  }

  li{
    flex-grow:1;
    flex-basis:200px;
    text-align:center;
    padding:25px;
    border:1px solid #222;
    margin:20px;
  }
</style>

注意

传数组和列表都算是传“引用”,即子组件数据更改,父组件的数据也会更改,而传String字符串仅仅是传值,不会同步更改。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值