第九讲===>父子组件的通信

  • 父传子

    • 父用子的时候通过属性传递
    • 子要声明props:['属性名'] 来接收
    • 收到就是自己的了,随便你用
      • 在template中 直接用
      • 在js中 this.属性名 用
  • 子传父

    • 子组件里通过$emit('自定义事件名',变量1,变量2)触发

    • 父组件@自定义事件名=‘事件名’监听

    • 子组件方法里  this.$emit('sendfather',val1,val2)触发自定义事件
      父组件里  <child @sendfather='mymethods'></child>
      
<!DOCTYPE html>
<html>
<head>
	<title>父子组件的通信</title>
</head>
<body>
	<div id="app">
		
	</div>

	<script type="text/javascript" src="vue.js"></script>
	<script type="text/javascript">
		//子组件定义好了props直接用
		var Child={
			template:`
				<div>
				我是子组件{{sendchild}}
				<button @click='sendparent'>我要反馈东西给父亲</button>
				</div>
			`,
			props:['sendchild'],
			methods:{
				sendparent(){
					this.$emit('baba','这是儿子组件给你的')
				}
			}

		}
		//父组件通过属性sendchild传递了数据给子组件
		var Parent={
			template:`
				<div>
				我是父组件{{ msg }}
				<child sendchild='父亲给你的' @baba='reserve'></child>

				</div>
			`,
			components:{
				Child
			},
			data(){
				return {
					msg:''
				}
			},
			methods:{
				reserve(val){
						this.msg=val
				}
			}
		}
		
		new Vue({
			el:'#app',
			components:{
				Parent
			},
			template:`
				<div>
				<parent></parent>
				</div>
			`,
			data(){
				return {

				}
			},
		})
	</script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/xl4ng/p/12580823.html