data: function () {
return {
translatedText: '2',
appKey: '47bb6e424790df89',
key: 'NH2VxBadIlKlT2b2qjxaSu221dSC78Ew',
salt: (new Date()).getTime(),
from: '',
to: 'en'
}
},
components: {
TranslateForm, TranslateText
},
methods: {
textTranslate: function (text, to) {
let vm = this
$.ajax({
url: 'http://openapi.youdao.com/api',
type: 'post',
dataType: 'jsonp',
data: {
q: text,
appKey: this.appKey,
salt: this.salt,
from: this.from,
to: to,
sign: md5(this.appKey + text + this.salt + this.key)
},
success: function (data) {
vm.$set(vm.$data, '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>
1、父组件拿到子组件传来的数据后开始通过api来请求数据
2、我用的是有道api http://ai.youdao.com/login.s api文档里对于api的使用已经很详细了,我在这里是第一次使用api,没觉得难
3、需要自己安装两个依赖:一个是jquery由于ajax请求api,一个是blueimp-md5在请求api时会用到里面的md5()
4、用vue.set将得到的结果绑定到translatedText这个变量,在这一步的时候我踩了两个坑
第一个坑:习惯了以前的写法,直接就这样给变量赋值,结果变量的值并未改变,这时我还不知到有Vue.set这个语法,后面百度才知道的(不认真看文档的下场)
success: function (data) {
this.translatedText = data.translation[0] console.log(this.translatedText)
}第二个坑:照着文档来写,然后报错了:this.$set is not a function,这里报错是因为success这个函数里的this指向的不是当前的VueModel
success: function (data) {
this.$set(this.$data, 'translatedText', data.translation[0])
}所以我在前面定义了一个vm变量来充当当前Model,然后就不报错了。
TranslateText.vue
<template>
<div id="TranslateText">
<p>{{translatedText}}</p>
</div>
</template>
<script>
export default {
name: 'TranslateText',
props: [
'translatedText'
]}
</script>
<style></style>props接收父组件传值来使用
最后
这个文章我自己看了一下,写的确实不好,许多地方不通顺,希望大家多多包涵










