javascript - VueJS如何用emit代替dispatch

标签 javascript vue.js vuejs2

我想从子组件向父组件发送信号。我不想使用 Vuex,因为就我的 VueJS 知识水平而言,Vuex 太复杂了。我正在使用单文件组件。

child.vue

<script>
export default {
name: 'ChildComponent',
methods: {
    // ajax post here ...
    if (response.data.status === 'accepted'){
      this.$emit('send-data', 'accepted')
    }

}

父级.vue

<script>
import ChildComponent from './ChildComponent.vue'
export default {
    name: 'Parent',
    data () {
      return {
        stage: 1
      }
    },
  components: {
      ChildComponent
  },
  // how can I replace 'events' with $on in a single file component and listen for events after all components have been created
  events: {
  'send-data': function (dataResponse) {
    if (dataResponse === 'accepted'){
      this.stage = 2
    }
  }
}

VueJS 文档中的示例显示了父级的类似内容:

var eventHub = new Vue()
created: function () {
  eventHub.$on('add-todo', this.addTodo)
  eventHub.$on('delete-todo', this.deleteTodo)
},

但我想随时监听事件,而不仅仅是创作。如何用 $on 函数替换父级“事件”?

最佳答案

如果您开始监听 created 上的事件,该事件将在组件的整个生命周期中起作用。或者,您可以在使用组件时使用 v-on@ 快捷方式设置要触发的事件。

示例

Vue.component('my-component', {
  template: '<div><button v-on:click="sendHello">hello</button></div>',
	
	methods:{
		sendHello: function(){
			console.log('hello');
          this.$emit('hello','hello')
		}
	}
});
new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!'
  },
	methods:{
		sayHi: function(){
			console.log('say hi')
		}
	}
})
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>VueJs</title>

</head>
<body>
<div id="app">
  <p>{{ message }}</p>
	<my-component v-on:hello='sayHi'></my-component>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>	
</body>
</html>

关于javascript - VueJS如何用emit代替dispatch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43027053/

相关文章:

javascript - Vuetify,如何通过双击 v-data-table 中的事件获取行

javascript - 如何在 ChartJS 中创建自定义图例

vue.js - 如何等待Vuex上传的数据?

vue.js - VueRouter 和元字段

javascript - 如果变量仅使用一次,则声明变量的原因

javascript - 使用 jQuery 动态添加的表单字段不会提交到服务器

javascript - 选择选项时如何自动设置表单中的输入值?

vue.js - Vue 的 img 标签上的 @error 是否监听 onerror 事件?

javascript - 将类添加到插槽范围

javascript - 注册 Controller 和服务 Angular JS?