前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >关于vue.js父子组件数据传递

关于vue.js父子组件数据传递

作者头像
用户1141560
发布2019-05-24 20:31:44
1.1K0
发布2019-05-24 20:31:44
举报
文章被收录于专栏:西安-晁州西安-晁州

vue.js中使用props down,events up的原则进行父子组件间的通信,先来记录下props down,看个例子:

代码语言:javascript
复制
<div id="app2">
  <child message="hello!"></child>
</div>

...

Vue.component('child', {
  // 声明 props
  props: ['message'],
  // 就像 data 一样,prop 可以用在模板内
  // 同样也可以在 vm 实例中像 “this.message” 这样使用
  template: '<span>{{ message }}</span>'
})

new Vue({
	el:"#app2"
});

以上定义了一个全局组件child,在app2的父级作用域中使用时,child组件定义了一个message属性,这样父组件在使用子组件的地方直接通过给child的message属性赋值即可将该值传递到子组件内部,从而输出模板内容:hello!,这里的“hello!”字符串是固定的,如果我们想传入的是app2作用域中的动态数值可以使用如下方式:

代码语言:javascript
复制
<div id="app2">
  <child v-bind:message="parentMsg"></child>
  <input v-model="parentMsg">
</div>

...

Vue.component('child', {
  // 声明 props
  props: ['message'],
  // 就像 data 一样,prop 可以用在模板内
  // 同样也可以在 vm 实例中像 “this.message” 这样使用
  template: '<span>{{ message }}</span>'
})

new Vue({
  el:"#app2",
  data:{
    parentMsg:""
  }
});

这样的话,子组件中的message值完全来自于父组件中的data.parentMsg,父组件的数据操作直接更新到子组件中。

再来看下events up的实例:

代码语言:javascript
复制
<div id="counter-event-example">
  <p>{{ total }}</p>
  <!-- 父组件可以在使用子组件的地方直接用 v-on 来监听子组件触发的事件,也就是这里的$.emit("increment")事件 -->
  <button-counter v-on:increment2total="incrementTotal"></button-counter>
  <button-counter v-on:increment2total="incrementTotal"></button-counter>
</div>

...

Vue.component('button-counter', {
  template: '<button v-on:click="increment">{{ counter }}</button>',
  data: function () {
    return {
      counter: 0
    }
  },
  methods: {
    increment: function () {
      this.counter += 1
      this.$emit('increment2total',{"admin":"############"})
    }
  },
})
new Vue({
  el: '#counter-event-example',
  data: {
    total: 0
  },
  methods: {
    incrementTotal: function (value) {
    	alert(JSON.stringify(value));
      this.total += 1
    }
  }
})

子组件模板中声明click事件,调用自身methods方法increment,increment里面通过$emit形式抛出一个事件到对应的子组件:on那里,查找到对应的父组件调用方法为incrementTotal,则直接调用该方法并传递参数。

关于vue.js后续一些学习心得体会均会在此处分享,一步步慢慢学吧。。。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-03-29 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档