VUE.JS父子组件传值,详细教程

// 子组件向父组件传值 emit

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例 - 菜鸟教程(runoob.com)</title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
	<div id="counter-event-example">
	  <button-counter @increment="incrementTotal"></button-counter> //@子组件需要emit的内容="父组件执行的时间"
	</div>
</div>

<script>
//子组件
Vue.component('button-counter', {
  template: '<button @click="increment1">{{ counter }}</button>',
  data: function () {
    return {
      counter: 0
    }
  },
  methods: {
    increment1: function () {
      this.$emit('increment',2)//子组件emit出对应内容,传递一个参数2
    }
  },
})
//父组件
new Vue({
  el: '#counter-event-example',
  data: {
    total: 0
  },
  methods: {
    incrementTotal: function (temp) {//父组件接收到emit消息,拿到temp参数2,并执行这个函数。
      this.total += temp
    }
  }
})
</script>
</body>
</html>

总结:子组件利用点击事件increment1触发,emit出事件increment,可以传递值2。父组件接到emit,并拿到传递来的值,执行对应事件incrementTotal。实现了从子组件到父组件的传递。

//父组件向子组件传值 prop

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例</title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
	//父组件传值hello,子组件定义好message接收
	<child message="hello!"></child>
</div>

<script>
// 子组件注册
Vue.component('child', {
  // 声明 props接收
  props: ['message'],
  // 就可以“this.message” 这样使用
  template: '<span>{{ message }}</span>'
})
// 创建根实例
new Vue({
  el: '#app'
})
</script>
</body>
</html>

总结,父组件 :子组件变量=父组件变量, 子组件中props:[子组件变量]就可以使用了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值