美文网首页
父子组件传值props & v-slot搭配使用

父子组件传值props & v-slot搭配使用

作者: 媛猿YY | 来源:发表于2021-03-23 14:21 被阅读0次

props:单个值的传递
v-slot:插槽可以传递一个Dom或单个值

OrderHeader.vue 子组件

<div class="title">
                <h2>{{ title }}<slot name="tip"></slot></h2>
            </div>

props: {
        title: String, //接收父组件传过来的值
    },

order.vue 父组件

<order-header :title="title">
            <template v-slot:tip>
                {{ tip }}
            </template>
        </order-header>
<script>
import OrderHeader from '../components/OrderHeader';
// @ is an alias to /src

export default {
    name: 'order',
    data() {
        return {
            title: '',
            tip: '',
        };
    },
    components: {
        OrderHeader,
    },
    mounted() {
        let path = this.$route.path;
        if (path == '/order/confirm') {
            this.title = '订单确认';
            this.tip = '请认真填写收货地址';
        } else if (path == '/order/list') {
            this.title = '订单列表';
            this.tip = '请谨防钓鱼链接或诈骗电话,了解更多>';
        } else if (path == '/order/pay') {
            this.title = '订单支付';
            this.tip = '请谨防钓鱼链接或诈骗电话,了解更多>';
        }
    },
};
</script>

子组件向父组件传递值

  • 在vue中,父子组件的关系可以总结为prop向下传递,事件向上传递。父组件通过prop给子组件下发数据,子组件通过事件给父组件发送信息。
  • 每个Vue实例都实现了事件接口:使用on(evntName)监听事件;使用emit(eventName,optionalPayload)触发事件。另外,父组件可以在使用子组件的地方直接用v-on来监听子组件触发的事件。

举例:

  • 父组件在组件上定义了一个自定义事件childFn,事件名为parentFn用于接受子组件传过来的message值。
<!-- 父组件 -->
<template>
    <div class="test">
      <test-com @childFn="parentFn"></test-com>
      <br/> 
      子组件传来的值 : {{message}}
    </div>
</template>

<script>
export default {
    // ...
    data() {
        return {
             message: ''
        }
    },
    methods: {
       parentFn(payload) {
        this.message = payload;
      }
    }
}
</script>
  • 子组件是一个buttton按钮,并为其添加了一个click事件,当点击的时候使用$emit()触发事件,把message传给父组件。
<!-- 子组件 -->
<template> 
<div class="testCom">
    <input type="text" v-model="message" />
    <button @click="click">Send</button>
</div>
</template>
<script>
export default {
    // ...
    data() {
        return {
          // 默认
          message: '我是来自子组件的消息'
        }
    },
    methods: {
      click() {
            this.$emit('childFn', this.message);
        }
    }    
}
</script>

相关文章

网友评论

      本文标题:父子组件传值props & v-slot搭配使用

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