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

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

<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作用域中的动态数值可以使用如下方式:

<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的实例:

<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后续一些学习心得体会均会在此处分享,一步步慢慢学吧。。。

原文地址:https://www.cnblogs.com/vipzhou/p/6639098.html