props
父组件向子组件传值,子组件调用
$emit
子组件调用父组件中定义的方法
父组件
<template>
<div id="app">
<h1>在线翻译</h1>
<TranslateForm @formSubmit='translateText' :title=msg />
<textarea v-text="translatedText" class="textarea" readonly="readonly"></textarea>
</div>
</template>
<script>
import TranslateForm from '@/components/TranslateForm'
export default {
name: 'App',
data() {
return {
msg: '请输入内容',
translatedText: ''
}
},
components:{
TranslateForm
},
methods:{
translateText (text, language) {
this.$axios.get('https://translate.yandex.net/api/v1.5/tr.json/translate?key=你自己的KEY&lang='+language+'&text='+text).then((response) => {
this.translatedText = response.data.text[0];
})
}
}
}
</script>
<style>
#app {
text-align: center;
}
.textarea {
width: 800px;
height: 200px;
margin: 20px auto;
display: block;
padding: 5px;
}
</style>
子组件(TranslateForm.vue)
<template>
<div id="translate-form">
<form>
<textarea class="textarea" v-model="textToTranslate" :placeholder="title"></textarea>
<select v-model="language" class="language">
<option value="en">英语</option>
<option value="ru">俄语</option>
<option value="ko">朝鲜语</option>
<option value="ja">日语</option>
<option value="es">西班牙语</option>
<option value="it">意大利语</option>
<option value="de">德语</option>
<option value="zh">中文</option>
</select>
<input type="submit" value="翻译" @click="formSubmit">
</form>
</div>
</template>
<script>
export default {
name: 'TranslateForm',
props: ['title'],
data () {
return{
textToTranslate:'',
language: 'en'
}
},
methods: {
formSubmit (e) {
this.$emit('formSubmit', this.textToTranslate, this.language);
e.preventDefault();
}
}
}
</script>
<style>
.language {
width: 200px;
height: 30px;
margin-right: 20px;
}
input[type="submit"] {
display: inline-block;
width: 120px;
height: 30px;
}
</style>
网友评论