有两个组件TranslateForm.vue和TranslateText.vue挂载在根组件时TranslateForm.vue成功渲染,TranslateText.vue只渲染出来一个<div></div>标签,控制台未报错
TranslateForm.vue
<template>
<div>
<!--加上页面修饰符,提交时就不回再重载页面-->
<form v-on:submit.prevent="formSubmit">
<input type="text" v-model="text" placeholder="输入需要翻译的内容"/>
<select>
<option value ="en">English</option>
</select>
<input type="submit" value="翻译"/>
</form>
</div>
</template>
<script>
export default {
name: 'TranslateForm',
data: function () {
return {
text: ''
}
},
methods: {
formSubmit: function () {
this.$emit('formSubmit', this.text)
}
}
}
</script>
<style></style>
TranslateText.vue
<template>
<div>
<p>111</p>
<h2>{{translatedText}}</h2>
</div>
</template>
<script>
export default {
name: 'TranslateText',
props: [
'translatedText'
]
}
</script>
<style></style>
APP.vue
<template>
<div id="app">
<h2>简单翻译</h2><span>简单/易用/便捷</span>
<TranslateForm v-on:formSubmit="textTranslate"></TranslateForm>
<TranslateText v-text="translatedText"></TranslateText>
</div>
</template>
<script>
import TranslateForm from './components/TranslateForm.vue'
import TranslateText from './components/TranslateText.vue'
import md5 from 'blueimp-md5'
import $ from 'jquery'
export default {
name: 'App',
data: function () {
return {
appKey: '47bb6e424790df89',
key: 'NH2VxBadIlKlT2b2qjxaSu221dSC78Ew',
salt: (new Date()).getTime(),
from: '',
to: 'en',
translatedText: ''
}
},
components: {
TranslateForm, TranslateText
},
methods: {
textTranslate: function (text) {
$.ajax({
url: 'http://openapi.youdao.com/api',
type: 'post',
dataType: 'jsonp',
data: {
q: text,
appKey: this.appKey,
salt: this.salt,
from: this.from,
to: this.to,
sign: md5(this.appKey + text + this.salt + this.key)
},
success: function (data) {
console.log(data.translation[0])
this.translatedText = data.translation[0]
}
})
}
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
引用方式改成以下:
使用上面这种方式,如果子组件中没有slot,里面的内容会被丢弃,不会渲染:
参考链接