Vue-node

Download and install node

First download Quguan network node

https://nodejs.org/zh-cn/

 

 Suggested administrator command line command to ensure the success rate

Installation cnpm

This is similar to the python pip, Package Manager command

# In other domestic sources, accelerate downloads
#管理员命令行: asl install -g cnpm --registry = https: // registry.npm.taobao.org 
# MacOS: sudo asl install -g cnpm --registry = https: // registry.npm.taobao.org

# Index npm instructions can be replaced cnpm
# npm install vuex => cnpm install vuex

vue cli environment: Scaffolding - command-line quickly create project

"""
cnpm install -g @vue/cli

If the error: npm cache clean --force This command is empty the cache processing


Creating project

Create a project

In the command line enter the path to the file you want to install
vue creat project name
// To enter the destination directory in advance (which projects should be created in the directory)
 // select Custom mode to create a project, select Router, Vuex plug

Specific configuration: vertical key switch, select the spacebar, the Enter key the next step
1. The second option to enter a custom configuration
2.Babel jsES6 syntax conversion ES5, Router routing Vuex Formatter formatting code data exchange component
3 has ... prompted to select the capital, did not suggest a default can be the first
. "" "

Start / Stop Project

RUN serve npm / Ctrl + c
 // To access the root directory of the project in advance

Packaging Project

RUN Build npm
 // packaging operation to be performed under the project root directory

pychar start the project

 

Project Directory

dist: packaged project directory (the package will generate)
node_modules: Project Dependencies
public: Shared Resources
src: project objectives, a place to write code
    - Assets: Resources
     - Components: Components
     - views: view component
     - App.vue: root element
     - main.js: Entrance JS
     - router.js: routing file
     - store.js: Status library
vue.config.js: project configuration file (no their new)

Rendering page components in the root component

————————————main.js—————————————
import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' Vue.config.productionTip = false // new Vue({ // router, // store, // render: h => h(App) // }).$mount('#app') new view ({ on: '#app' , router:router, store:store, render:function (h) { return h(App) } });

Here './store' can be directly written '@ / store', dot represents the current directory, on behalf src @

Can omit the extension, the file name can not be repeated, rewritten here instantiation is es6 write us here with es5

<!-- Main.vue 主页组件 -->
<template>
    <div class="main">
        <h1>{{ title }}</h1>
    </div>
</template>

<script>
    export default {
        name: "Main",
        data: function () {
            return {
                title: ' Home '
            }
        }
    }
</script>

<style scoped>
    .main {
        height: 100vh;
        background-color: #eeeee;
    }
    h1 {
        margin: 0;
        color: black;
    }
</style>
<-! App.vue root element -> 
< Template > 
    < div ID = "App" > 
        <-! 3. Use -> 
        < the Main > </ the Main > 
    </ div > 
</ Template > 
< Script > 
    // 1. import 
    import from the Main ' @ / views / the Main ' 
    Export default {
         // 2. need to register the sub-assembly 
        components: {
            Main: Main
        }
    }
</script>
<style>
    html, body {
        margin: 0;
    }
</style>

Routing  router.js

In the root component design Jump page navigation bar

<template>
    <div id="app">
        <ul class="nav">
            <li>
                <router-link to="/">主页</router-link>
            </li>
            <li>
                <router-link to="/goods">商品页</router-link>
            </li>
            <li>
                <router-link to="/user">个人页</router-link>
            </li>
        </ul>
        <!--里面不用写东西可以用单标签-->
        <router-view/>
    </div>
</template>
<script>
    import Main from '@/views/Main'

    export default {
        components: {
            Main: Main
        }
    }
</script>
<style>
    .nav {
        height: 60px;
        background-color: #3e3e3e;
    }

    .nav li {
        float: left;
        text-align: center;
        height: 60px;
        width: 100px;
        line-height: 60px;
    }

    .nav li:hover {
        background-color: beige;
    }

      .nav li a  {
        /**/
          color: black;
          text-decoration: none;
          font: bold 20px/40px 'STSong';
    }

    html, body, ul, h1 {
        margin: 0;
    }

    ul {
        list-style: none;
    }


</style>


<!--<template>-->
<!--<div id="app">-->
<!--<div id="nav">-->
<!--<router-link to="/">Home</router-link> |-->
<!--<router-link to="/about">About</router-link>-->
<!--</div>-->
<!--<router-view/>-->
<!--</div>-->
<!--</template>-->

<!--<style>-->
<!--#app {-->
<!--font-family: 'Avenir', Helvetica, Arial, sans-serif;-->
<!-- -webkit-font-smoothing: antialiased;-->
<!-- -moz-osx-font-smoothing: grayscale;-->
<!--text-align: center;-->
<!--color: #2c3e50;-->
<!--}-->
<!--#nav {-->
<!--padding: 30px;-->
<!--}-->

<!--#nav a {-->
<!--font-weight: bold;-->
<!--color: #2c3e50;-->
<!--}-->

<!--#nav a.router-link-exact-active {-->
<!--color: #42b983;-->
<!--}-->
<!--</style>-->

 

 

 

这里的router-link就是一个a标签

这里data是被vue渲染的,所以拿vue来做网页别人来爬网页就比较难,都是vue自己渲染的

创建三个页面组件

import Vue from 'vue'
import Router from 'vue-router'
// import Home from './views/Home.vue'
import Main from './views/Main.vue'
import Goods from './views/Goods.vue'
import User from './views/User.vue'

Vue.use(Router)

export default new Router({
    mode: 'history',
    base: process.env.BASE_URL,
    routes: [
        {
            path: '/',
            name: 'main',
            component: Main
        },
        {
            path: '/goods',
            name: 'goods',
            component: Goods
        },
        {
            path: '/user',
            name: 'user',
            component: User
        }

  ]
})

配置完页面就会转跳

配置路由

现在可以从后台拿数据渲染到前端页面上,页面一加载的时候就要拿,这里涉及到声明周期钩子mounted,

最好是用window开头,这些都是基于浏览器运行

 axios

这个就是Vue(ajax)

生命周期钩子

  • 表示一个vue实例从创建到销毁的这个过程,将这个过程的一些时间节点赋予了对应的钩子函数

  • 钩子函数: 满足特点条件被回调的方法

new Vue({
    el: "#app",
    data: {
        msg: "message"
    },
    beforeCreate () {
        console.log("实例刚刚创建");
        console.log(this.msg
                    
    },
    created () {
        console.log("实例创建成功, data, methods已拥有");
        console.log(this.msg);
    },
    mounted () {
        console.log("页面已被vue实例渲染, data, methods已更新");
    }
    // 拿到需求 => 确定钩子函数 => 解决需求的逻辑代码块
})

前后台交互

然后把main.js放在圆形里面,圆形就是js的面向对象

 

 

// 请求后台
let _this = this;
this.$ajax({
    url: 'http://127.0.0.1:8000/goods/',
    method: 'post',
    params: {
        info: '前台数据'
    }
}).then(function (result) {
    let data = result.data;
    // this 指向的是then的function
    _this.aaaa = data;
})
let _this = this
this.$ajax({
    method: 'post',
    url: 'http://127.0.0.1:5000/loginAction',
    params: {
        usr: this.usr,
        ps: this.ps
    }
}).then(function(res) {
    // this代表的是回调then这个方法的调用者(axios插件),也就是发生了this的重指向
    // 要更新页面的title变量,title属于vue实例
    // res为回调的对象,该对象的data属性就是后台返回的数据
    _this.title = res.data
}).catch(function(err) {
    window.console.log(err)
})
params是携带的参数,then就是success就是回调,catch就是如果出现错误,ajax里面错误是error这里的catch就是arror


后台开始写接口,先要注释掉csrf,以后需要自定义认证

先用get请求

 

 

 结果报了cors的错误跨域问题

 后台收到了前台发过来的信息

 

 前台的跨域问题其实很简单,后台来着不惧,如果发现这个网站不是同域的就不给你返回数据,后端可以接收前端发送的信息。

解决方法:一对一解决,如果是来自某些域的话就是合法的,否则就是不合法的,现在不知道来自哪些域

后台解决跨域问题

什么是跨域

'''
通常情况下,A网页访问B服务器资源时,不满足以下三个条件其一就是跨域访问
1. 协议不同 http协议和https协议
2. 端口不同 一个主机上面启动两个应用所以端口不一样产生了跨域问题
3. 主机不同 你在华东服务器,我再华南服务区就主机不同
'''

Django解决跨域

'''
安装django-cors-headers模块

在settings.py中配置
# 注册app
INSTALLED_APPS = [
    ...
    'corsheaders'
]
# 添加中间件
MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware'
]
# 允许跨域源
CORS_ORIGIN_ALLOW_ALL = True

这样配置完重新启动,后台信息就发送到过去了

<template>
    <div class="goods">
        <h1>商品页</h1>
        <h2>{{ msg }}</h2>
    </div>
</template>

<script>
    export default {
        name: "Goods",
        data: function () {
            return {
                msg: '',
            }
        },
        beforeCreate() {
            window.console.log('开始创建Goods组件')
        },
        created() {
            window.console.log('创建Goods组件完毕')
        },
        mounted() {
            window.console.log('Goods组件渲染完毕');
            //请求后台
            let _this =this;
            this.$ajax({
                method: 'post',
                url: 'http://127.0.0.1:8000/goods/',
                params: {
                    info: '前台数据'
                }

            }).then(function (result) {
                let data = result.data;
                _this.msg = data;

            })
        }
    }
</script>

<style scoped>
    .goods {
        height: 100vh;
        background-color: darkkhaki;
    }
</style>

这里在then里面不能直接写this这里的this是回调函数里面的this不再是视图函数的this,再发送请求之前需要把视图函数的this保存一下。这里的this代表是views对象

 

 

Guess you like

Origin www.cnblogs.com/zhengyuli/p/11103505.html