美文网首页
三.父子组件传值(return很重要)

三.父子组件传值(return很重要)

作者: 小柠有点萌 | 来源:发表于2021-06-17 13:03 被阅读0次

    父传子(vue2同)props

    父组件A (return函数
     <b-list  :message = 'message'></b-list>
    <script>
    import Blist from './B.vue'
    export default {
      name: 'A',
      components: {
        Blist
      },
      setup(props, components) {
        const message = [{num: 3}]
        return {
          message  // 这边也要return出来
        }
      }
    }
    </script>
    
    子组件B
    <p v-for="item in message">{{item.num}}</p>
    <script>
    export default {
      name: 'B',
      props: ['message']
    }
    </script>
    

    子传父context.emit

    tip:1.父子组件都要return,否则不生效

    父组件A (return函数
     <b-list @getMessage="showMessage"></b-list>
    <script>
    import Blist from './B.vue'
    export default {
      name: 'A',
      components: {
        Blist
      },
      setup(props, components) {
        console.log(props, components)
        const showMessage = (value) => {
          console.log(value)
        }
        return {
          showMessage  // 这边也要return出来
        }
      }
    }
    </script>
    
    子组件Breturn很重要,点击事件要return出去
    setup(props, context) {
        // 点击加入购物车
        const cartClick = () => {
          // 通过自定义事件回传值
          context.emit('getMessage', 2)
        }
        const state = reactive({
          cartClick  // 点击事件要return过去,防止事件不生效
        })
    

    相关文章

      网友评论

          本文标题:三.父子组件传值(return很重要)

          本文链接:https://www.haomeiwen.com/subject/drccyltx.html