Vue项目简介
最终效果:Vue通过axios发请求给Django后台,Django返回数据给Vue
创建项目:
创建vue项目: -安装node.js -vue脚手架 -vue create 项目名字 pycharm开发vue项目 -需要安装vue.js插件 -setting--->plugins--->左下方install---->去搜索---->下载--->重启 -运行vue项目 -editconfigration--->+--->npm--->run serve vue目录结构: -node_modules:项目依赖(以后项目要传到git上,这个不能传) -publish--->index.html 是总页面 -src :项目 -assets:静态资源 -components:组件 -views:视图组件 -APP.vue:根组件 -main.js :总的入口js -router.js :路由相关,所有路由的配置,在这里面 -store.js :vuex状态管理器 -package.json:项目的依赖,npm install 是根据它来安装依赖的 每个组件会有三部分: -template -style -script
新建组件:
在views文件下创建一个新的组件
<template> <div class="course"> <button class="btn" @click="ck">点击查看</button> <h1>课程列表</h1> <p>{{ course}}</p> <p>{{info}}</p> <p v-for="c in course">{{c}}</p> </div> </template> <script> export default { data: function () { return { course: ['aa', 'bb'], info: ['郑棒', '徐都会'] } }, methods: { clk: function () { alert('123') }, ck: function () { let _this = this; this.$http.request({ url: 'http://127.0.0.1:8001/test/', method: 'post', }).then(function (response) { _this.course = response.data }).catch(function () { alert('请求失败') }) } }, } </script>
我们需要在router中配置路由
import Course from './views/other.vue' export default new Router({ mode: 'history', base: process.env.BASE_URL, routes: [ { path: '/course', name: 'course', component: Course, } ] })
并且在主组件上配置
data对应的数据页面上可以直接通过{{ 变量名 }}使用
data: function () { return { course: ['aa', 'bb'], info: ['郑棒', '徐都会'] } }
method对应的是一些函数方法,tmeplate中的标签可以直接绑定(@click="ck")
methods: { clk: function () { alert('123') }, ck: function () {
// 为了能直接在组件直接能使用course所以要将this赋值进去,不然在里面直接使用this指向的是该方法 let _this = this; this.$http.request({ url: 'http://127.0.0.1:8001/test/', method: 'post', }).then(function (response) { _this.course = response.data }).catch(function () { alert('请求失败') }) } },
为pycharm配置Vue高亮:
若没有下载过,右边框中有一个install按钮点击安装即可