Vue2 子组件向父级传递数据

导读:本篇文章讲解 Vue2 子组件向父级传递数据,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Vue 示例</title>
</head>

<body>
  <div id="app">
    <p>总数:{{total}}</p>
    <my-component @increase="handleGetTotal" @reduce="handleGetTotal"></my-component>
  </div>
  
  <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
  
  <script>
  
    Vue.component('my-component', {
	  template: '\
	  <div>\
	    <button @click="handleIncrease">+1</button>\
		<button @click="handleReduce">-1</button>\
	  </div>',
	  data: function() {
	    return {
		  counter: 0
		}
	  },
	  methods: {
	    handleIncrease: function() {
		  this.counter++;
		  this.$emit('increase', this.counter);
		},
	    handleReduce: function() {
		  this.counter--;
		  this.$emit('reduce', this.counter);
		},
	  }
	});
  
    var app = new Vue({
	  el: '#app',
	  data: {
	    total: 0
	  },
	  methods: {
	    handleGetTotal: function (total) {
		  this.total = total;
		}
	  }
	});
  </script>
  
</body>
</html>

注意:组件里data方法与,Vue对象里data的不同!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之家整理,本文链接:https://www.bmabk.com/index.php/post/17305.html

(0)
小半的头像小半

相关推荐

极客之家——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!