这篇文章主要介绍了vue最简单的前后端交互示例,现在分享给大家,也给大家做个参考。一起过来看看吧。
后端怎么和vue.js配合?
Vue 的核心库只关注视图层,那么怎么实现和后端进行交互呢,需要借用到axios库,下面是一个官方的示例:
<!DOCTYPE html> <html> <head> <title>My first Vue app</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script> </head> <body> <div id="watch-example"> <p> Ask a yes/no question: <input v-model="question"> </p> <p>{{ answer }}</p> </div> <script> var watchExampleVM = new Vue({ el: '#watch-example', data: { question: '', answer: 'I cannot give you an answer until you ask a question!' }, watch: { // 如果 question 发生改变,这个函数就会运行 question: function (newQuestion, oldQuestion) { this.answer = 'Waiting for you to stop typing...' this.debouncedGetAnswer() } }, created: function () { // `_.debounce` 是一个通过 Lodash 限制操作频率的函数。 // 在这个例子中,我们希望限制访问 yesno.wtf/api 的频率 // AJAX 请求直到用户输入完毕才会发出。想要了解更多关于 // `_.debounce` 函数 (及其近亲 `_.throttle`) 的知识, // 请参考:https://lodash.com/docs#debounce this.debouncedGetAnswer = _.debounce(this.getAnswer, 500) }, methods: { getAnswer: function () { if (this.question.indexOf('?') <div style="color:transparent">来源gaodai.ma#com搞#代!码网</div>=== -1) { this.answer = 'Questions usually contain a question mark. ;-)' return } this.answer = 'Thinking...' var vm = this axios.get('https://yesno.wtf/api') .then(function (response) { vm.answer = _.capitalize(response.data.answer) }) .catch(function (error) { vm.answer = 'Error! Could not reach the API. ' + error }) } } }) </script> </body> </html>
可以看见,上面代码中,在methods里有一个getAnswer方法,它使用axios库发送了一个get请求,请求后端的api。
然后使用 chromium 浏览器打开这个文件。下面是运行效果:
这里访问的后端是 https://yesno.wtf/api ,它传回的数据时 json 格式的,如果直接访问它,得到的结果如下:
这就是vue和后端配合的一个简单案例,在这个示例中,它使用 axios 库从 https://yesno.wtf/api 获取数据。同时,在这个例子中,它还使用 lodash 限制刷新频率。
后端和vue.js配合使用的总结:
-
vue项目引入axios
-
在methods中创建一个请求函数
-
函数内使用axios请求后端api
-
后端处理完数据返回结果给前端,格式为json格式
-
前端拿到数据再进行相应处理
更多Vue.js相关技术文章,请访问Vue.js答疑栏目进行学习!
以上就是后端怎么和vue.js配合?的详细内容,更多请关注gaodaima搞代码网其它相关文章!