深入理解VueJS:组件通信的几种方式

2023-05-18 09:14:32

深入理解VueJS:组件通信的几种方式

// 父组件向子组件传递props
Vue.component('Child', {
  props: {
    message: String
  }
})

// 子组件使用props

// 父组件传递props

// 子组件通过$emit派发事件向父组件通信

// 父组件监听子组件事件

// 父组件处理事件
methods: {
  handleMessage(msg) {
    console.log(msg)
  }
}

// 通过$refs调用子组件的方法

methods: {
  handleChildClick() {
    this.$refs.child.methodName()
  }
}

// 使用vuex来实现组件间数据共享
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++
    }
  },
  getters: {
    getCount(state) {
      return state.count
    }
  }
})

// 子组件从vuex获取数据

// 子组件修改vuex中的数据
  • 作者:
  • 原文链接:
    更新时间:2023-05-18 09:14:32