Vue.JS:获取一言数据
在看Vue.JS的监听部分与方法调用部分的内容,写了一个小的代码;
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
< !DOCTYPE html> <html> <head> <!-- 字符集 --> <meta charset="UTF-8"/> <!-- 单页 | 标题 --> <title>请随机给我一段话 | Leviathan·利维坦</title> <!-- 通过UNPKG获得VUE的引用 --> <!-- <script src="https://unpkg.com/vue"> --> <!-- 开发环境版本,包含了有帮助的命令行警告 --> <!-- <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"> --> <!-- 生产环境版本,优化了尺寸和速度 --> <script src="https://cdn.jsdelivr.net/npm/vue"></script> <!-- 因为 AJAX 库和通用工具的生态已经相当丰富,Vue 核心代码没有重复 --> <!-- 提供这些功能以保持精简。这也可以让你自由选择自己更熟悉的工具。 --> <script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js"></script> </head> <body> <!-- 显示处理 --> <div id="ui-area"> <button v-on:click="get_words">现在就给我一段话!</button> <p>{{ finally_words }}</p> <p>是否和之前的话不一样了?【{{ has_been_changed }}】</p> </div> <!-- 逻辑处理 --> <script> var UIAreaVM = new Vue({ el: "#ui-area", data: { finally_words: "I cannot give you a words until you click the button!!", has_been_changed: '' }, watch: { // 如果,参数【finally_words】发生了改变,这里的代码就会运行 finally_words: function(newData, oldData){ this.has_been_changed = "已经发生了改变:" + new Date().toLocaleString() // this.debouncedGetAnswer() } }, created: function() { this.debouncedGetAnswer = _.debounce(this.get_words, 500) }, methods: { get_words: function() { this.finally_words = "【I am loading...】" var vm = this axios.get('https://v1.hitokoto.cn/') .then(function(response){ vm.finally_words = _.capitalize( response.data.hitokoto + "【来自作品:" + response.data.from + " / 人物:" + response.data.from_who + "】" ) }) .catch(function(error){ vm.finally_words= "Error!! Couldnot reach the API. " + error }) } } }) </script> </body> </html> |
[……]