主要操作技能:

     1 .父组件调用子组件的时候,绑定动态属性 <v-header :title="title"></v-header>

     2.在子组件中通过props来接受父组件传的数据 

          props: ['title','msg','run','home'] 

          props: { //可以指定属性具体的数据类型哦!
            'title': String,
            'msg': Number,
            'run': Function,
            'home': Object
          } 

   3.直接在子组件中使用

编写代码:

Header.vue

<template>
	<div>
		<h2>{{xmsg}}====>{{title}}-----{{msg}}</h2>
		<button @click="run('传参数')">执行父组件的方法</button><br /><br />
		
		<button @click="getParent()">获得父组件的属性和方法</button>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				xmsg: '头部组件'
			}
		},
		methods: {
			getParent(){
//				alert(this.title);
//				alert(this.home.title);
				this.home.run('hello');
			}

		},
		props: ['title','msg','run','home']  //指定父组件中的属性
	}
</script>

App.vue

<template>
	<!--所以的内容多要被根节点包含起来 -->
	<div id="home">
		<v-header :title="title" :msg='msg' :run="run" :home="this"></v-header><br /><br /> {{msg}}
		<br />
	</div>
</template>

<script>
	/**
	 * 父组件给子组件传值
	 *   1.父组件调用子组件的时候,绑定动态属性
	 *    <v-header :title="title"></v-header>
	 * 
	 *   2.在子组件中通过props来接受父组件传的数据
	 * 
	 * 
	 */

	import Header from './Header.vue'
	export default {
		data() { //数据
			return {
				msg: '我是首页组件',
				title: '父组件参数' //父组件数据
			}
		},
		components: {
			'v-header': Header
		},
		methods: {

//			run() {
//              alert('我是父组件的run方法!');
//			}
			run(result) {
                alert('我是父组件的run方法--->'+result);
			}
		}

	}
</script>

注意: 可以指定属性的数据类型 (效果忽略)

<template>
	<div>
		<h2>{{xmsg}}====>{{title}}-----{{msg}}</h2>

		<button @click="run('aaa')">父组件方法</button>
		<button @click="getHome()">获得父组件属性</button>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				xmsg: '头部组件'
			}
		},
		methods: {
			getHome() {
				alert(this.home.title);
			}
		},
		props: { //可以指定属性具体的数据类型哦!
			'title': String,
			'msg': Number,
			'run': Function,
			'home': Object
		} //指定父组件中的属性
	}
</script>

 

效果:

父组件传值给子组件(属性)

子组件的属性名msg不能父组件的属性名msg相同哦!否则会出现异常的哦!

 

修改后,就不会发生这个异常了!

子组件执行父组件的方法

子组件执行父组件属性和方法(传对象)

 

 

Logo

前往低代码交流专区

更多推荐