Vue父子组件传值的方法

1.父向子传值props

父组件:<child :inputName="name">

子组件:

(1)props: {

   inputName: String,

   required: true

  }

(2)props: ["inputName"]


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

子组件:

 <span>{{childValue}}</span>

 <!-- 定义一个子组件传值的方法 -->

  <input type="button" value="点击触发" @click="childClick">


 export default {

  data () {

   return {

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

   }

  },

  methods: {

   childClick () {  

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

   }

  }

 }


父组件

<!-- 引入子组件 定义一个on的方法监听子组件的状态-->

<child v-on:childByValue="childByValue"></child>

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调用

<template>

  <div @click="parentMethod">

    <children ref="c1"></children>

  </div>

</template>


<script>

  import children from 'components/children/children.vue'

  export default {

    data(){

      return {

      }

    },

    computed: {

    },

    components: {      

      'children': children

    },

    methods:{

      parentMethod() {

        console.log(this.$refs.c1) //返回的是一个vue对象,可以看到所有添加ref属性的元素

        this.$refs.c1.childMethods();

      }

    },

    created(){

    }

  }

</script>

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


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


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



5.vue 全局事件(eventBus)

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


在文件列表里 <span >{{ item }}<button @click="down(item)">下载</button></span>


另一组件的监听

6.兄弟之间的传值Vuex

在state里定义数据和属性

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

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

猜你喜欢

转载自blog.csdn.net/lianwenxiu/article/details/87898688