Vue父子组件传值的方法

1.父向子传值props

父组件:

子组件:

(1)props: {

   inputName: String,

   required: true

  }

(2)props: ["inputName"]


2.子组件向父组件传值$emit

子组件:

 {{childValue}}

 

  


 export default {

  data () {

   return {

    childValue: '我是子组件的数据'

   }

  },

  methods: {

   childClick () {  

    this.$emit('childByValue', this.childValue)

   }

  }

 }


父组件

methods: {

   childByValue: function (childValue) {

    // childValue就是子组件传过来的值

    this.name = childValue

   }

  }

}


3.父组件调用子组件的方法通过ref

在DOM元素上使用$refs可以迅速进行dom定位,类似于$("selectId")

使用this.$refs.paramsName能更快的获取操作子组件属性值或函数

子组件:

methods:{

childMethods() {

        alert("I am child's methods")

}

}


父组件: 在子组件中加上ref即可通过this.$refs.method调用


4.可以通过$parent和$children获取父子组件的参数


我们可以使用$children[i].paramsName 来获取某个子组件的属性值或函数,$children返回的是一个子组件数组

Vue父子组件传值的方法_第1张图片


那么子组件怎么获取修改父组件的数据内容?这需要使用$parent

Vue父子组件传值的方法_第2张图片

Vue父子组件传值的方法_第3张图片


5.vue 全局事件(eventBus)

在main.js里:window.eventBus = new Vue();//注册全局事件对象


在文件列表里 {{ item }}

Vue父子组件传值的方法_第4张图片


另一组件的监听

Vue父子组件传值的方法_第5张图片

6.兄弟之间的传值Vuex

在state里定义数据和属性

在 mutations里定义函数fn,在页面通过

this.$store.commit('fn',params)来触发函数,Vuex在这里不做详细介绍了

你可能感兴趣的:(vue)