vue 组件的简单学习(2)--子组件向父组件传值

上篇文章中学了 简单的展示vue子组件,那么子组件中的值如何传递到父组件中呢

1 背景表述:此时你已经写了一个子组件 子组件内容很简单只有一个button按钮。

                在父组件中引用了子组件,则在父组件中展示出了这个按钮。

当我在父组件页面,点击这个按钮时,我想要把子组件中的变量name的值传到父组件中。

请看以下子组件代码

<template>
    <div id="users">
     <button @click="change">change</button>
    </div>
</template>


<script>

    export default {
        name:'users',
        data() {
            return {
                 name:"子  to  父"
            };
        },
        methods:{
            change:function(){
                this.$emit("chuan",this.name);
            }
        }
    }
</script>

<style>

</style>
View Code

以上代码中:

当我点击 button  按钮时,会触发事件调用change方法。

在change方法中this.$emit("chuan",this.name); 注册了一个方法chuan(名字随意起),带一个参数name。

接下来看父组件代码

<template>
  <div class="hello1">
<users v-on:chuan="come($event)"></users>
    
  </div>
</template>

<script>

  export default {
  name: 'HelloWorld',
 
    methods:{
            come:function(value){
             
        }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
View Code

以上代码中

<users v-on:chuan="come($event)"></users> 

引用子组件,绑定的方法chuan (在刚刚子组件中注册的名字)

chuan 调用come方法,所以在方法中写个com方法。

这样子组件中的name值,就传到了父组件的come方法(value)中。

猜你喜欢

转载自www.cnblogs.com/hhxylm/p/10636438.html
今日推荐