vue子组件和父组件传值

vue子组件和父组件传值

近期在学习vue,总结了一下子组件和父组件间传值的方法:

  • 父组件向子组件传值
  • 子组件向父组件传值

父组件向子组件传值

父组件向子组件传递数据主要通过props来进行传递。子组件想使用子组件的方法,要通过$emit来调用。

示例

在父组件中使用子组件,并且向其传递数据,子组件同时调用父组件的方法

页面中:
<div id="app">
        <ul>
            <people-item
                    v-for="people in peoples"
                    :key="people.id"
                    :people="people"
                    @my-event="showContent"
            ></people-item>
        </ul>
    </div>
js代码:
    //注册一个组件
    Vue.component('people-item',{
        props: ['people'],
       template: '<li @click="getContent">{{ people.name }}</li>',
        methods: {
            getContent() {
                this.$emit('my-event');
            }
        }
    });
    //实例化
    var vm = new Vue({
        el: '#app',
        data: {
            peoples: [
                {
                    id: 1,
                    name: '张三'
                },
                {
                    id: 2,
                    name: '李四'
                }
            ]
        },
        methods: {
          showContent() {
            console.log('获取数据');
          }
        }
    })

效果

点击后出现

 获取数据

子组件向父组件传值

父组件使用子组件的数据和方法,主要通过$refs来调用,但是必须给组件通过ref来指定一个唯一标识。

示例


<div id="app">
        <p>子组件的数据:{{ info }}</p>
        <todo-item ref="child"></todo-item>
</div>

//注册一个组件
 Vue.component('todo-item',{
        template: '<span>子组件</span>',
        data() {
            return {
                info: 'hello'
            }
        },
        methods: {
            childFun(msg) {
                console.log(msg);
            }
        }
    });
 //实例化
    var vm = new Vue({
        el: '#app',
        data: {
            msg:'父组件调用子组件方法',
            info: ''
        },
        methods: {
            getChildFun() {
              this.info = this.$refs.child.info;
              this.$refs.child.childFun(this.msg)
            }
        },
        mounted() {
            this.getChildFun();
        }
    })

效果

这里写图片描述
这里写图片描述

猜你喜欢

转载自blog.csdn.net/u010359143/article/details/80734672
今日推荐