通过$emit 实现子组件向父组件通信
官网定义:vm.$emit( event, arg )
解释:子组件中通过$emit 绑定一个自定义事件event(formSubmit1),当这个这个语句被执行到的时候,就会将参数arg(textToTranslate)传递给父组件,父组件通过@event(@formSubmit1)监听并接收参数(textToTranslate)
父组件:App.vue
<template>
<div id="app">
<TranslateForm @formSubmit1="translateText"></TranslateForm>
</div>
</template>
<script>
import TranslateForm from './components/TranslateForm.vue'
export default {
name: 'App',
components: {
TranslateForm
},
methods:{
translateText:function (text) {
alert(text);
}
}
}
</script>
子组件:TranslateForm.vue
<template> <div> <form @submit="formSubmit"> <input type="text" v-model="textToTranslate" placeholder="请输入"> <select> <option value="en">English</option> </select> <input type="submit" value="翻译"> </form> </div> </template> <script> export default { data:function(){ return { textToTranslate:"" } }, methods:{ formSubmit:function (e) { this.$emit("formSubmit1",this.textToTranslate); e.preventDefault(); } } } </script> 转自:https://www.jb51.net/article/140581.htm中的第3个