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.

     

  • 相关阅读:
    【杭电】[2071]无限的路
    【杭电】[1161]Eddy's mistakes
    【杭电】[1859]最小长方形
    【杭电】[2083]简易版之最短距离
    【CodeForces】[614A]Link/Cut Tree
    【杭电】[2076]夹角有多大
    【杭电】[2055]An easy problem
    【杭电】[2036]改革春风吹满地
    【杭电 】[2040]亲和数
    【杭电】[2044]一只小蜜蜂...
  • 原文地址:https://www.cnblogs.com/zhupanpan/p/9606064.html
Copyright © 2011-2022 走看看