zoukankan      html  css  js  c++  java
  • vue2.0父子组件传值

    在vue开发中,我们经常需要在子组件使用父组件的数据,父组件使用子组件的数据,其实vue提供了这两个方法。

    1.子组件向父组件传值,

    在父组件内声明变量,子组件接受用props:

    例如.父组件: 

    <template>
    <div>
    {{message }}{{num}}
    <br />
    <hello :num="num"></hello>
    </div>
    </template>
    <script>
    import hello from "@/components/HelloWorld"
    export default {
    data(){
    return{
    message:"我是父组件我要传的值是:",
    num:10,
    }
    },
    components:{
    hello
    }
    }
    </script>

    注册组件后在组件标签绑定你要传的值。

    子组件

    <template>
    	<div>
    	{{message}}{{num}}
    	</div>
    </template>
    <script>
    	export default {
    		//接受父元素的值用props
    			props:["num"],
    		data(){
    			return{
    			message:"我是子组件我接受的值是:",
    			}
    		},
    	}
    </script>
    

      子组件用props接受。结果如图所示

    2.子组件向父组件传值

    先在子组件定义,用$emit(),接受两个参数,一个是事件名,也就是绑定在父组件的事件,第二个是传的值,我把这个方法绑定在一个button按钮上,点击按钮传值。

    子组件:

    <template>
        <div>
        {{message2}}{{count}}
        <br />
        <button @click="chuanzhi">像父组件传值</button>
        </div>
    </template>
    <script>
        export default {
            data(){
                return{
                message2:"我是子组件我要传的值是:",
                count:20
                }
            },
            methods:{
                chuanzhi(){
                    //向父元素传值用$emit
                this.$emit("child",this.count);
                }
            }
        }
    </script>

    父组件先定义一个空值num2,当点击的时候去用num2接收子组件传过来的值,把子组件的方法绑定在注册的子组件标签上。代码如下

    父组件:

    <template>
        <div>
        {{message }}{{num2}}
        <br />
        <hello @child="getvalue"></hello>
        </div>
    </template>
    <script>
        import hello from "@/components/HelloWorld"
        export default {
            data(){
                return{
                message:"我是父组件我接受的值是:",
                num2:''
                }
            },
            components:{
                hello
            },
            methods:{
                getvalue(val){
                    this.num2=val;
                }
            }
        }
    </script>

    点击按钮,父组件接受的值为20.

     

  • 相关阅读:
    作业七:用户体验设计案例分析
    作业五:需求分析
    作业四:结对编程 词频统计
    作业四:结对编程,词频统计
    作业三:词频统计
    作业2
    Github注册过程
    ArrayList的说明及简单用法
    Java类中成员变量、局部变量、静态变量的区别
    AspNetCore.SignalR的JwtBearer认证
  • 原文地址:https://www.cnblogs.com/zhupanpan/p/9606064.html
Copyright © 2011-2022 走看看