Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

65. Vue 父子组件传值 #65

Open
wqjiao opened this issue Jun 19, 2020 · 0 comments
Open

65. Vue 父子组件传值 #65

wqjiao opened this issue Jun 19, 2020 · 0 comments

Comments

@wqjiao
Copy link
Owner

wqjiao commented Jun 19, 2020

  • 父组件向子组件传值
    通过 prop 向下传递,子组件中通过 props 接收预期的数据,并定义好类型:
// 静态属性
<child title="我是一个子标题"  />

// 动态属性,需要 v-bind 绑定
<child :title="title"  />
  • 子组件向父组件传值
    通过 事件 向上传递,使用事件接口监听或触发:
// 监听事件
$on(evntName)
// 触发事件:eventName: 事件名;optionalPayload: 参数
$emit(eventName, optionalPayload)
  • 兄弟组件之间传值
    方式一:借助共同的父组件进行 prop 传值
    方式二:采用 eventbus,注意 -> 避免参数命名重复
  <div>
      <child-2 />
      <child-1 />
  </div>
import Event from '../bus'
export default {
  name: 'Child1',
  props: ['btnName'],
  methods: {
    clickHandle () {
      Event.$emit('update:count')
    }
  }
}
import Event from '../bus'
export default{
  name: 'Child2',
  data () {
    return {
      count: 0
    }
  },
  created () {
    Event.$on('update:count', () => {
      ++this.count
    })
  }
}
  • 非兄弟/父子组件传值
    采用 eventbus 的方式。

注意:以上传值方式都有一个共同的方式: 状态管理(如: vuex)等

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant