vue----cli项目父组件向子组件传值

思路:
(1)在父组件中定义数据
(2)在父组件中通过v:bind绑定
(3)在子组件中通过props接收

代码:
(1)

 data() {
    return {
      users: [
        { name: "mark", position: "web开发", show: false },
        { name: "mark", position: "web开发", show: false },
        { name: "mark", position: "web开发", show: false },
        { name: "mark", position: "web开发", show: false },
        { name: "mark", position: "web开发", show: false },
        { name: "mark", position: "web开发", show: false },
        { name: "mark", position: "web开发", show: false },
        { name: "mark", position: "web开发", show: false },
        { name: "mark", position: "web开发", show: false },
        { name: "mark", position: "web开发", show: false },
        { name: "mark", position: "web开发", show: false }
      ],
      title:'传递的是一个值包括number、Boolean、string'
    }
  },

在父组件中定义数据

(2)
v-bind:users=“users” 第一个users是名称,为了使能在子组件中调用。第二个users是传的值

<users v-bind:users="users"></users>


import Users from "./components/Users"


 components: {
    users: Users
    }
   

在父组件中绑定

(3)在子组件中调用

<template>
  <div class="users">
    <ul>
        <li v-for="(item,index) in users" :key="index" v-on:click="item.show=!item.show">
          <h2>{{item.name}}</h2>
          <h3 v-show="item.show">{{item.position}}</h3>
        </li>    
     </ul>
      <button v-on:click="deleteUser">删除</button>
  </div>
</template>

<script>
export default {
  name: 'users',
  props:{
    users:{
      type:Array,
      required:true
    }
  },
  data () {
    return {

    }
    
  },
  methods: {
    deleteUser:function() {
      this.users.pop();
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
ul {
 display: flex;
 flex-wrap: wrap;
 list-style-type: none;
 padding: 0;
}
li {
  flex-grow: 1;
  flex-basis: 200px;
  text-align: center;
  padding:30px;
  border: 1px solid #222;
  margin: 10px;
}
.users{
  width: 100%;
  max-width: 1200px;
  margin: 40px auto;
  padding:0 20px;
  box-sizing: border-box;
}
</style>

第一种写法比较简单 不太正规,推荐使用第二种官方文档写法

props:["users"] 

第二种写法

props:{
    users:{
      type:Array,
      required:true
    }
  }

在子组件中调用

运行结果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值