Vue的常用传值方式、父传子、子传父 非父子

在这里插入图片描述
父组件向子组件传值是利用props

子组件中的注意事项:props:[‘greetMsg’],注意props后面是[]数组可以接收多个值,不是{}。

                            且此处的greetMsg用greet-msg会报错,记住需用驼峰法命名

非父子组件进行传值
非父子组件之间传值,需要定义个公共的公共实例文件bus.js,作为中 间仓库来传值,不然路由组件之间达不到传值的效果。

import Vue from 'vue'
export default new Vue()
//组件A:
<template>
  <div>
    A组件:
    <span>{{elementValue}}</span>
    <input type="button" value="点击触发" @click="elementByValue">
  </div>
</template>
<script>
  // 引入公共的bug,来做为中间传达的工具
  import Bus from './bus.js'
  export default {
    data () {
      return {
        elementValue: 4
      }
    },
    methods: {
      elementByValue: function () {
        Bus.$emit('val', this.elementValue)
      }
    }
  }
</script>
//组件B:
<template>
  <div>
    B组件:
    <input type="button" value="点击触发" @click="getData">
    <span>{{name}}</span>
  </div>
</template>
<script>
  import Bus from './bus.js'
  export default {
    data () {
      return {
        name: 0
      }
    },
    mounted: function () {
      var vm = this
      // 用$on事件来接收参数
      Bus.$on('val', (data) => {
        console.log(data)
        vm.name = data
      })
    },
    methods: {
      getData: function () {
        this.name++
      }
    }
  }
</script>

Vue常用的传值方式就介绍完了,如果有什么不明白的,可以在评论区留言哦!

猜你喜欢

转载自blog.csdn.net/mlonly/article/details/87857241
今日推荐