vue 子传父 父传子

一.父组件向子组件传值

1.创建子组件,在src/components/文件夹下新建一个Child.vue
2.Child.vue的中创建props,然后创建一个名为message的属性

父组件
<template>
    <div>
        <h1>我是父组件!</h1>
        <child v-bind:message="msg"></child>
    </div>
</template>
<script>
    import Child from './components/Child.vue'
    export default {
//子组件引用
        components: {
            Child
        },
        data() {
            return {
                msg: '我是子组件!'
            }
        }
    }
</script>

子组件
<template>
    <h3>{{message}}</h3>
</template>
<script>
    export default {
        props: ['message']
    }
</script>

 

 

 

子传父

父组件通过绑定自定义事件,接受子组件传递过来的参数
子组件通过$emit触发父组件上的自定义事件,发送参数

父组件通过$on监听事件,事件处理函数的参数则为接收的数据

子组件通过$emit可以触发事件,

第一个参数为要触发的事件,第二个事件为要传递的数据

sync修饰符:对一个 props 进行双向绑定

<template>
    <div class="parent">
        <h2>{{ msg }}</h2>
        <p>父组件接手到的内容:{{ username }}</p>
        <child psMsg="我是你爸爸" @transfer="getUser"></child>
        <!-- 监听子组件触发的transfer事件,然后调用getUser方法 -->
    </div>
</template>
<script>
    import Child from './components/Child'
    export default {
        name: 'App',
        data () {
            return {
                msg: '父组件',
                username:'',
            }
        },
        components:{Child},
        methods:{
            getUser(msg){
                this.username= msg
            }
        }
    }
</script>
<template>
    <div class="Child">
        <p>{{ sonMsg }}</p>
        <p>子组件接收到内容:{{ psMsg }}</p>
        <!--<input type="text" v-model="user" @change="setUser">-->
        <button @click="setUser">传值</button>
    </div>
</template>
<script>
    export default {
        name: "Child",
        data(){
            return {
                sonMsg:'子组件',
                user:'子传父的内容'
            }
        },
        props:['psMsg'],
        methods:{
            setUser:function(){
                this.$emit('transfer',this.user)//触发transfer方法,this.user 为向父组件传递的数据
            }
        }
    }
</script>

 

posted @ 2022-05-12 19:03  しっ  阅读(58)  评论(0)    收藏  举报