Skip to content

【vue】组件的使用(3)自定义事件$on/$emit #19

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

Open
Kelichao opened this issue Feb 3, 2017 · 4 comments
Open

【vue】组件的使用(3)自定义事件$on/$emit #19

Kelichao opened this issue Feb 3, 2017 · 4 comments
Labels

Comments

@Kelichao
Copy link
Owner

Kelichao commented Feb 3, 2017

自定义事件

父组件是使用 props 传递数据给子组件,但如果子组件要把数据传递回去,应该怎样做?那就是自定义事件!

每个vue实例都有触发事件的方法

  • 使用 $on(eventName) 监听事件
  • 使用 $emit(eventName) 触发事件

父组件可以在使用子组件的地方直接用 v-on 来监听子组件触发的事件。然后再对应子组件方法执行处触发事件,两者缺一不可。

<!-- 父组件 -->
<div id="app">
  <!-- 子组件 -->
  <!-- 父组件直接用 v-on 来监听子组件触发的事件。 -->
  <!-- 需跟子组件中的$emit组合使用 -->
  <mycon v-on:son_method="father_method"></mycon>
</div>
// 子组件
Vue.component('mycon', {
  template: '<button v-on:click="son_method">子按钮</button>',
  methods: {
  	// 按钮点击时候触发事件
    son_method: function () {
      this.counter += 1;
 	  console.log("son");
      // 这句话来触发事件
      // 必须跟模板中的v-on配合使用
      this.$emit('son_method');
    }
  },
});

// 父组件
new Vue({
  el: "#app",
  methods: {
    father_method: function () {
      console.log("father");
    }
  }
});

绑定原生事件(适用于组件)

有时候,你可能想在某个组件的根元素上监听一个原生事件。可以使用 .native 修饰 v-on 。例如:

<my-component v-on:click.native="doTheThing"></my-component>

使用自定义事件的表单输入组件

表单输入组件,使用 v-model 来进行数据双向绑定。要让组件的 v-model 生效,它必须:

  • 接受一个 value 属性
  • 在有新的 value 时触发 input 事件
<div id="app">
    <input v-model="something">
    <!-- 
		分两步:
		第一步:通过v-bind给输入框赋值
		第二步:通过v-on:input事件执行一句something = $event.target.value更改something
     -->
    <input v-bind:value="something" v-on:input="something = $event.target.value">
    <!-- 简写 -->
   <input v-bind:value="something" v-on:input="something = arguments[0]"><input>
</div>
new Vue({
  el: "#app",
  data:{
  	something:123
  },
  watch: {
  	something:function() {
  		console.log(234)
  	}
  }
});

非父子组件通信

在简单的场景下,使用一个空的 Vue 实例作为中央事件总线:

var bus = new Vue()

// 触发组件 A 中的事件
bus.$emit('id-selected', 1)

// 在组件 B 创建的钩子中监听事件
bus.$on('id-selected', function (id) {
  // ...
})
@Kelichao Kelichao added the vue label Feb 3, 2017
@Kelichao Kelichao changed the title 【vue】组件的使用(3) 【vue】组件的使用(3)自定义事件 Feb 3, 2017
@Kelichao Kelichao changed the title 【vue】组件的使用(3)自定义事件 【vue】组件的使用(3)自定义事件$on/$emit Feb 3, 2017
@PengZhao12
Copy link

so

@yemaoteng
Copy link

Thanks

@Vivianluolita
Copy link

thanks

@sueblue
Copy link

sueblue commented Jun 12, 2018

tks

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

No branches or pull requests

5 participants