当前位置 博文首页 > 超负荷小生的博客:vue-父子组件之间的传值,入门实例

    超负荷小生的博客:vue-父子组件之间的传值,入门实例

    作者:[db:作者] 时间:2021-09-08 19:41

    父组件传值给子组件

    第一步:创建子组件,定义props属性,用来监听msg变量的值的变化

    <template>
    	<div class="hello">
    		<h1>{{ msg }}</h1>
    	</div>
    </template>
    <script>
    	export default {
    		name: 'HelloWorld', //对父子传值没有影响
    		//定义props属性,
    		props: {
    			msg:{
    				type: String
    			}
    			//只有一个type属性可以简写
    			//msg:String
    		}
    	}
    </script>
    <style scoped>
    </style>
    

    第二步:引用子组件:import导入组件;在components注册组件; 在template中使用组件;这三步的名称要保持一致!!!!

    <template>
      <div class="home">
        <img alt="Vue logo" src="../assets/logo.png">
        <HelloWorld :msg="msgg"/> <!--msg要和子组件中的props属性保持一致;msgg是要传递的值 -->
    	<button @click="changeMsg()">改变</button>
      </div>
    </template>
    <script>
    import HelloWorld from '@/components/HelloWorld.vue' //导入组件
    export default {
      name: 'home',
      data(){
    	  return{
    		msgg: "Welcome to Your Vue.js App"//msgg默认值
    	  }
      },
      components: {
        HelloWorld
      },
      methods:{
    	  changeMsg(){
    		  this.msgg="change message"//点击按钮后改变msgg的值
    	  }
      }
    }
    </script>
    

    效果,显示的默认msgg的值;
    在这里插入图片描述点击按钮在父组件的值将msgg的值改变,传递给子组件
    在这里插入图片描述

    子组件传值给父组件

    第一步:编写方法使用$emit的方式给父组件传值

    <template>
    	<div class="hello">
    		<input v-model="sonChangMsg" />
    		<button @click="sendSonChangeMsg()">发送信息给父组件</button>
    	</div>
    </template>
    
    <script>
    	export default {
    		name: 'HelloWorld', //对父子传值没有影响
    		data() {
    			return {
    				sonChangMsg: ""
    			}
    		},
    		methods: {
    			sendSonChangeMsg() {
    				this.$emit('childFn', this.sonChangMsg); //(名称,值) 名称必须和父组件保持一致
    			}
    		}
    	}
    </script>
    
    <style scoped>
    </style>
    

    第二步:父组件中,使用组件时,名称要和子组件设置的名称保持一致

    <template>
      <div class="home">
        <img alt="Vue logo" src="../assets/logo.png">
    	<h1>{{fromSonMsg}}</h1><!--默认是没有值,当子组件有值并传递过来时才会出现值 -->
    	<HelloWorld @childFn="sonChangeMsg"></HelloWorld> <!--@名称=“方法”-->
      </div>
    </template>
    <script>
    import HelloWorld from '@/components/HelloWorld.vue'
    export default {
      name: 'home',
      data(){
    	  return{
    		fromSonMsg:""
    	  }
      },
      components: {
        HelloWorld
      },
      methods:{
    	  sonChangeMsg(childData){ //childData中包含着子组件传递过来的值
    		  this.fromSonMsg=childData;
    	  }
      }
    }
    </script>
    

    效果:默认子组件上面是没有值的
    在这里插入图片描述子组件传递以后出现值(输入框中输入值以后)出现值
    在这里插入图片描述

    cs