Vue 组件之间传值总结

1、通过路由带参数传值

   ① A组件通过query把id传给B组件         

1

this.$router.push({path:'/B',query:{id:1}})

  ② B组件接收 

1

this.$route.query.id

2、父组件向子组件传值

使用props向子组件传递数据

子组件部分:child.vue

1

2

3

4

5

6

7

8

9

10

11

12

<template>

  <div>

    <ul>

      <li v-for='(item,index) in nameList' :key='index'>{{item.name}}</li>

    </ul>

  </div>

</template>

<script>

export default {

  props:['nameList']

}

</script>

父组件部分:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

<template>

  <div>

    <div>这是父组件</div>

    <child :name-list='names'></child> 

  </div>

</template>

<script>

import child from './child.vue'

export default {

  components:{

    child

  },

  data(){

    return{

      names:[

        {name:'柯南'},

        {name:'小兰'},

        {name:'工藤新一'}

      ]

    }

  }

}

</script>

3、子组件向父组件传值

    子组件主要通过事件向父组件传递数据:

    子组件部分:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<template>

  <div>

    <ul>

      <li v-for='(item,index) in nameList' :key='index'>{{item.name}}</li>

    </ul>

    <Button @click='toParent'>点击我</Button>

  </div>

</template>

<script>

export default {

  props:['nameList'],

  methods:{

    toParent(){

      this.$emit('emitData',123)

    }

  }

}

</script>

父组件部分:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

<template>

  <div>

    <div>这是父组件</div>

    <child :name-list='names' @emitData='getData'></child> 

  </div>

</template>

<script>

import child from './child.vue'

export default {

  components:{

    child

  },

  data(){

    return{

      names:[

        {name:'柯南'},

        {name:'小兰'},

        {name:'工藤新一'}

      ]

    }

  },

  methods:{

    getData(data){

      console.log(data); //123

    }

  }

}

</script>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值