当前位置:   article > 正文

Go实战Gin+Vue+微服务打造秒杀商城第四课 VUE的使用与渲染_gin+vite+vue3实现服务端渲染

gin+vite+vue3实现服务端渲染

前端vue的使用

node环境搭建

使用node.js可以快速的创建出vue-cli的脚手架

一、nvm安装(Node Version Manager)

1.nvm的作用

  • nvm是用来用来管理nodeJs版本的。假设有多个项目,每个项目依赖的node版本不一样,这个时候就可以用到nvm来管理node版本

2.安装

3.配置环境变量

  • 把nvm安装的路径添加到path路径下即可

4.验证

  • cmd中运行nvm命令

5.nvm的常用命令

  • nvm install [version]:安装指定版本的node.js 。
  • nvm use [version]:使用某个版本的node。
  • nvm list:列出当前安装了哪些版本的node。
  • nvm uninstall [version]:卸载指定版本的node。
  • nvm node_mirror [url]:设置nvm的镜像。
  • nvm npm_mirror [url]:设置npm的镜像。

二、node安装

1.安装指定版本的node

  • nvm install 10.16.0

2.设置nvm源

  • nvm node_mirrorhttps://npm.taobao.org/mirrors/node/设置nvm的镜像。
  • nvm npm_mirrorhttps://npm.taobao.org/mirrors/npm/设置npm的镜像。

npm的使用(Node package manager)

npm已经在安装Node的时候顺带装好了

一、作用

  • NodeJs的包管理工具
  • npm可以根据每个包之间的依赖关系,把所有依赖的包都下载下来并管理起来

二.常用命令:

nvm use 10.16.0(使用node后才可以使用npm)

1.查看版本:npm -v

2.初始化:npm init 进入指定项目目录执行,会生成一个package.json文件,保存本项目中用到的包

三、安装需要的包

1.本地安装:安装在node的安装目录

npm install vue      # 本地安装
  • 1

2.全局安装:安装在本项目目录

npm install vue  -g    # 全局安装
  • 1

注意:–save参数会将安装的包记录到package.json中

四、使用淘宝镜像

安装cnpm:npm install -g cnpm --registry=https://registry.npm.taobao.org
  • 1

以后就可以使用cnpm来安装包

四、安装vue/cli

cnpm install -g @vue/cli     #全局安装vue-cli
  • 1

五、手动安装npm

有时候使用nvm安装完node后,npm没有跟着安装,这时候可以到https://github.com/npm/cli/releases下载6.10.1的版本。然后下载完成后,解压开来,放到v10.16.0/node_modules下,然后修改名字为npm,并且把npm/bin中的npm和npm.cmd两个文件放到v10.16.0根目录下。

vue-cli脚手架

一、vue-cli介绍

vue-cli是一个vue的工具,可以快速构建vue项目,并且创建好了一下脚手架代码,很方便

二、vue-cli安装

工具没必要每个项目都安装一次,所以安装到全局即可

npm install -g @vue/cli

更新:npm update -g @vue/cli
  • 1
  • 2
  • 3

三、vue-cli创建项目

在存放项目路径下执行:

vue create [项目名称]
  • 1

也可以使用镜像安装

vue create -r https://registry.npm.taobao.org [项目名称]

或者在文件中设置:在当前用户目录下,找到.npmrc,然后设置registry=https://registry.npm.taobao.org。
  • 1
  • 2
  • 3

四、项目结构介绍

1.node_modules:本地安装的包的文件夹。

2.public:项目出口文件。

3.src:项目源文件:

  • assets:资源文件,包括字体,图片等。
  • components:组件文件。
  • App.vue:入口组件。
  • main.js:webpack在打包的时候的入口文件。

4.babel.config.js:es*转低级js语言的配置文件。

5.package.json:项目包管理文件。

注意:vscode安装vetur包用来识别.vue文件

五、启动项目

可以在package.json文件中找到命令
npm run serve
  • 1
  • 2

组件定义

一、组件

二、样式

样式默认适用于所有页面,如果指向适用于当前页面,就使用scoped

<
style scoped
>
<
/style
>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

Element UI

Element UI组件库使用 element ui组件库是由饿了么前端团队专门针对vue框架开发的组件库,专门用于电脑端网页的。因为里面集成了很多组件,所以使用他可以非常快速的帮我们实现网站的开发。

注:vant是针对移动端的组件库

vue3.x 1.安装:

进入项目目录,执行: vue add element 2.使用

main.js中: import { createApp } from ‘vue’ import ElementUI from ‘element-ui’; import ‘element-ui/lib/theme-chalk/index.css’; import App from ‘./App.vue’

createApp(App).use(ElementUI).mount(‘#app’)

组件中使用:

这是一个按钮 vue2.x 1.安装:

课程中用到的版本是2.12.0,为了跟课程环境保持一致,安装的时候指定版本:

npm install element-ui@2.12.0 --save 2.引入:

引入的时候也是分成两种,一种是全部引入,一种是按需引入。这里我们跟大家介绍按需引入。

3.安装相关依赖包:

需要借助babel-plugin-component这个库,才能实现按需引入。安装的命令为:

npm install babel-plugin-component --save-dev。

4.配置:

在babel.config.js中添加以下配置:

module.exports = { “presets”: [ “@vue/app” ], “plugins”: [ [ “component”, { “libraryName”: “element-ui”, “styleLibraryName”: “theme-chalk” } ] ] } 5.使用:

然后在项目中可以进行使用了。先进行导入,然后进行组件注册,最后再使用:

ant-design-vue组件库使用

一、安装

npm i --save ant-design-vue@next             // 2.0.0-beta.10
  • 1

二、使用

1.main.js中

import { createApp } from 'vue'
import Antd from 'ant-design-vue';
import 'ant-design-vue/dist/antd.css';
import App from './App.vue'

createApp(App).use(Antd).mount('#app')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

2.组件中

script:
    import ant from "ant-design-vue";


    components: {
        [ant.name]:ant,
    }



template:
<
a-button type="danger"
>
按钮
<
/a-button
>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

官方文档地址:https://2x.antdv.com/components/

数据交互 VUE渲染

发送请求:axios

  • 官方文档:http://www.axios-js.com/zh-cn/docs/

路由控制:vue-router

  • 官方文档:https://router.vuejs.org/zh/

vue-router路由管理

vue -router 是vueJs官方的路由管理器

官方文档:https://router.vuejs.org/zh/api/

一、安装

npm install vue-router@4.0.0-alpha.4 --save

注意:出现“export 'createWebHistory' was not found in 'vue-router'”错误,是因为版本问题

没问题的版本:
    vue:3.0.0-beta.1     3.0.0
    vue-router:4.0.0-alpha.6      4.0.0-beta-.13


或者:
    vue:3.0.0-alpha.10
    vue-router:4.0.0-alpha.4


课程中的版本:
    vue:3.0.0
    vue-router:4.0.0-alpha.6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

二、使用

在src下新建router.js文件,内容如下:

import {createRouter,createWebHistory} from "vue-router"

const webHistory = createWebHistory()


const router = createRouter({
    history:webHistory,
    routes:[

        {
            path:"/",
            name:"index",
            component:=> import('./App.vue')
             children:[
                {
                    path:"home",
                    name:"Home",
                    component:() => import('./component/Home')  或者这种,不提前import
                },
            ]


        },

    ]
}
  • 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

axios的使用

一、安装

npm install axios --save
  • 1

二、使用

1.get请求

// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
  .then(function (response) {   // 成功的回调
    console.log(response);
  })
  .catch(function (error) {  // 失败的回调
    console.log(error);
  });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

2.get请求加参数

// 上面的请求也可以这样做
axios.get('/user', {    // 参数是在配置中加,配置中还可以指定header等信息
    params: {  
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

3.post请求

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

4.使用统一配置

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});


instance.get('/user', {    // 参数是在配置中加,配置中还可以指定header等信息
    params: {  
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

get请求

一、axios的两种回调

第一种:匿名函数

then(function(data){
    console.log(data);
})
  • 1
  • 2
  • 3

第二种:箭头函数

then((data) =>
 {
    console.log(data)
})
  • 1
  • 2
  • 3
  • 4

匿名函数和箭头函数的区别:

  • 匿名函数的this指针指向->函数操作的本身
  • 箭头函数的this指针指向->组件

所有要想回显数据到组件,得用箭头函数

二、mounted函数

生命周期函数和浏览器渲染过程挂钩

生命周期函数是否获取dom节点是否获取data是否获取methods
beforeCreate
created
beforeMount
mounted
created(){
    this.TestAxios();
},
  • 1
  • 2
  • 3

三、重定向

main.js中设置router全局属性
    app.config.globalProperties.$router = router

需要重定向的地方:
    this.$router.push("/home");
  • 1
  • 2
  • 3
  • 4
  • 5

四、回显服务器返回的数据

注意区别axis的回显:

1.map数据

<span>用户名:</span><br>
<span>msg</span>

data(){
    return {
         name:"",
         age:""
    }
},

// 使用箭头函数
this.$ajax.get("/chapter11/api_axios").then((data) => {
     console.log(data)
     this.name = data.data.name

}).catch(function((data) => {
     console.log(data);
})


2.数组或切片
<span v-for="a in arr" :key="a">
     <p></p>
</span>

注意:2.2.0版本以上,当在使用v-for时,key是必须的
  • 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

五:动态路由

router

path:"/book_detail/:id",
  • 1

template

<router-link :to="{name:'book_detail',params:{id:book.id}}"></router-link>
  • 1

获取参数

this.$route.params

this.$route.params.id
  • 1
  • 2
  • 3

解决跨域请求

中间件

package middle_ware

import (
    "github.com/gin-gonic/gin"
    "net/http"
)

// 解决跨域请求问题
func CrosMiddleWare(c *gin.Context)  {
    method := c.Request.Method

    c.Header("Access-Control-Allow-Origin", "*")
    c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
    c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
    c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
    c.Header("Access-Control-Allow-Credentials", "true")

    //放行所有OPTIONS方法
    if method == "OPTIONS" {
        c.AbortWithStatus(http.StatusNoContent)
    }
    // 处理请求
    c.Next()


}
  • 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

post请求

onSubmit() {
      alert(this.form.name);
      alert(this.form.password)
      this.$axios.post('/chapter11/tetPostData', qs.stringify({
            name: this.form.name,
            password: this.form.password,
        })).then(function (response) {
                console.log(response);
            }).catch(function (error) {
                console.log(error);
        });
    },
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

文件上传

一、单文件上传

onSubmit() {

        const formData = new FormData();
        formData.append("name",this.form.name);
        formData.append("password",this.form.password);
        formData.append("upload_file",document.querySelector('input[type=file]').files[0])

        this.$axios.post('/chapter11/getFile',formData).then(function (response) {
                    console.log(response);
                }).catch(function (error) {
                    console.log(error);
            });
    },
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

二、多文件上传

onSubmit() {

        const formData = new FormData();
        formData.append("name",this.form.name);
        formData.append("password",this.form.password);

        const files = document.getElementsByClassName('files')

        for(let i=0;i<files.length;i++){
            formData.append("upload_files",files[i].files[0])

        }

      this.$axios.post('/chapter11/getFiles',formData).then(function (response) {
                console.log(response);
            }).catch(function (error) {
                console.log(error);
        });
    },
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/457475
推荐阅读