Vue工程化搭建

Posted xue_yun_xiang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Vue工程化搭建相关的知识,希望对你有一定的参考价值。

一、vue-cli

cli: Command Line 命令行工具,vue-cli就是vue的命令行工具,也称之为脚手架,使用vue-cli提供的各种命令可以拉取、创建、运行我们需要使用到的框架,比如webpack、Element UI、Element Admin等等。那么要想使用vue-cli命令,需要先安装node.js。

vue 工程化搭建 使用vue-cli 完成

1、安装vue-cli前置工作

vue-cli 安装需要npm,npm 需要 node.js

1、安装node.js

是一个服务器,也是一个开发环境,也是一个框架

简单立即可以使用node.js 完成后台服务的开发(和tomcat sevlet一样)

在这里插入图片描述

2、安装npm

npm 可以简单认为,是一个包管理工具(类似java 中maven),同时可以安装一些插件(vue-cli)
在node.js 开发环境中已经默认配置了 npm,不需要安装

在这里插入图片描述

2、安装vue-cli

npm install vue-cli -g

install 安装
vue-cli vue-cli 插件
-g    golable 全局安装 系统中所有位置都可以使用

安装目录
在这里插入图片描述

npm 是包管理工具,他可以下载依赖jar 包 去中央仓库,有可能比较慢,可以配置淘宝镜像仓库
maven包管理工具,他可以下载依赖jar 包 mavnen 默认是去中央仓库 ,也可以配置阿里云镜像

安装淘宝npm 镜像(不强制)

npm install -g cnpm --registry=https://registry.npm.taobao.org

# 使用nmp  安装cnpm  使用的镜像是淘宝镜像

后续所有使用npm 的地方都可以使用 cnpm来替换(使用淘宝镜像)

npm 常用命令

npm intall 安装插件、依赖的jar 包
npm run dev 运行工程,以开发模式运行
nmp build 构建工程

二、创建vue工程

1、初始化工程
在这里插入图片描述
在这里插入图片描述

vue init webpack myproject1
vue init 初始vue工程
webpack 骨架 ,就类似 java 创建maven-web工程选择 webapp
myproject1 工程名

在这里插入图片描述
在这里插入图片描述
工程目录:
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

三、组件

vue工程化中的组件 都是以 .vue 结尾

1、由三部分组成:

1、布局

<template>
	<div></dic>  // 只能有一个根div
</template>

2、js 代码块

<script>
export default {  // 将当前 HelloWorld.vue  组件 导出
  name: 'HelloWorld', //导出的组件名字 HelloWorld
  data () {    // 当前组件的数据  类似 以前 学习  data :{ msg:'xxxx'},在组件中data必须以函数的形式返回
    return {
      msg: '12  准时吃饭 么?真的吃饭么'
    }
  }
}
</script>

注意:

在组件中data必须以函数的形式返回

3、css

当前组件的样式,和你普通 配置html 样式一样的

<!-- Add "scoped" attribute to limit CSS to this component only
 scoped 当前只针对 当前组件 HelloWorld.vue
 -->
<style scoped>
h1, h2 {
  font-weight: normal;
}

</style>

App.vue 是vue 工程的入口根组件,他和main.js 组合成为工程的入口
所有看到的内容都有app.vue 进行包裹展示
当前的应用就是单页面应用—》只有一个index.html
在这里插入图片描述

2、工程化声明组件

1、声明全局组件

1、在components 目录下创 MyContent.vue

<template>

  <div>
       <h1>自定义组件  </h1>
       title:{{title}}

  </div>

</template>

<script>
    export default {
        name: "MyContent",
        data(){
            return {
                title:'xxxxxTile'
            }
        }
    }
</script>

<style scoped>

</style>

2、在main.js 声明全局组件

// 引入自定义组件
import MyContent from "./components/MyContent";
// 声明全局组件
Vue.component("MyContent",MyContent);

3、在App.vue 使用组件

在这里插入图片描述

2、声明局部组件

在这里插入图片描述

3、自定义组件传递参数

在这里插入图片描述
在这里插入图片描述

四、Vue-router 路由

1、实例

1、在工程目录下安装路由模块

npm install vue-router -s

npm install --save vue-router

2、创建两个组件

Home.vue

<template>
    <div>
        <h1>home</h1>
    </div>
</template>

<script>
    export default {
        name: "Home"
    }
</script>

<style scoped>

</style>

Product.vue

<template>
    <div><h1>product</h1></div>
</template>

<script>
    export default {
        name: "Product"
    }
</script>

<style scoped>

</style>

3、创建src/router/index.js

import Vue from 'vue'

import Router from 'vue-router'

// 引入组件
import Home from "../components/Home";
import Product from "../components/Product";

// 使用router
Vue.use(Router);


export  default new Router({

  routes:[
    {
      path:'/Home',
      mame:"Home",
      component:Home
    }, {
      path:'/Product',
      mame:"Product",
      component:Product
    }
  ]

})

4、在main.js中引入路由模块

import  router from  './router'




/* eslint-disable no-new */
new Vue({
  el: '#app',
  components: { App },
  template: '<App/>',
  router
})

在这里插入图片描述

2、router 接收参数

1、修改Product.vue

在这里插入图片描述

2、修改src/router/index.js

在这里插入图片描述

3、传递参数App.vue

在这里插入图片描述

3、动态添加路由

 addRouter:function () {
            this.$router.push("/Product/2");
        }

在这里插入图片描述

五、vuex

1、概述

Vuex 是一个专为 Vue.js 应用程序开发的 状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化

2、安装

npm install vuex --save

3、实例

1、创建src/store/index

import Vue from "vue";

import Vuex from 'vuex'
Vue.use(Vuex)

const state= {
  // 获取user 状态
  // this.$store.state.user
    user:{
      name:'xiaoming'
    }
}


const getters={
    // 实时监听 state 值的最新状态,注意这里的 getters 可以理解为计算属性
    // this.$store.getters.getUser // 获取数据
    getUser(state){
      return state.user
    }

}

const mutations={

    // this.$store.commit('updateUser',user)// 同步修改
    updateUser(state,user){
        state.user = user;
    }
}

const actions={
  // this.$store.dispatch('asyncUpdateUser',user) // 异步加载
   asyncUpdateUser(context,user){
      context.commit('updateUser',user)
   }

}

export default  new Vuex.Store({
  state,
  getters,
  mutations,
  actions
})


2、在main.js 修改

// 引入vuex
import Vuex from 'vuex'
Vue.use(Vuex)
import store from './store'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  components: { App },
  template: '<App/>',
  router,
  store
})

在这里插入图片描述

3、在App.vue 添加按钮点击事件测试

 get:function () {
            alert(this.$store.state.user.name)
        },
        getter:function () {
            alert(this.$store.getters.getUser.name)
        },
        update:function () {

            this.$store.commit('updateUser',{name:'xxx'});
        },
        asyncUpdate:function () {
            this.$store.dispatch('asyncUpdateUser',{name:'xxx-async'})
        }

在这里插入图片描述

4、解决刷新界面数据丢失问题

问题描述:

Vuex 的状态存储是响应式的,当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。但是有一个问题就是:vuex 的存储的数据只是在页面的中,相当于我们定义的全局变量,刷新之后,里边的数据就会恢复到初始化状态。但是这个情况有时候并不是我们所希望的。

解决方案:
监听页面是否刷新,如果页面刷新了,将 state 对象存入到 sessionStorage 中。页面打开之后,判断 sessionStorage 中是否存在 state 对象,如果存在,则说明页面是被刷新过的,将 sessionStorage 中存的数据取出来给 vuex 中的 state 赋值。如果不存在,说明是第一次打开,则取 vuex 中定义的 state 初始值。

在App.vue中添加

 mounted() {
        // window.addEventListener('unload', this.saveState);
        window.addEventListener('unload', this.saveState);// 界面刷线时保存到sessionStorage
    },
    methods:{
        saveState() {// 调用该方法
            sessionStorage.setItem('state', JSON.stringify(this.$store.state));
        },
    	。。。
    }    

src/store/index.js 修改

// const state= {
//   // 获取user 状态
//   // this.$store.state.user
//     user:{
//       name:'xiaoming'
//     }
// }
const state = sessionStorage.getItem('state') ? JSON.parse(sessionStorage.getItem('state')) : {
  user: {
    name: 'ddd'
  }
};

六、Axios

1、概述

Axios 是一个开源的可以用在浏览器端和 NodeJS 的异步通信框架,她的主要作用就是实现 AJAX 异步通信,其功能特点如下:

  • 从浏览器中创建 XMLHttpRequests
  • 从 node.js 创建 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求数据和响应数据
  • 取消请求
  • 自动转换 JSON 数据
  • 客户端支持防御 XSRF(跨站请求伪造)

为什么要使用 Axios?

由于 Vue.js 是一个 视图层框架 并且作者(尤雨溪)严格准守 SoC (关注度分离原则),所以 Vue.js 并不包含 AJAX 的通信功能,为了解决通信问题,作者单独开发了一个名为 vue-resource 的插件,不过在进入 2.0 版本以后停止了对该插件的维护并推荐了 Axios 框架

2、安装vue axios

npm install --save axios vue-axios

3、实例

1、在main.js 引入

import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)

2、在App.vue发起请求

1、axios.get请求

axiosByGet:function () {
            // var vm = this;
            // this.axios.get('http://localhost:8090/findStudentById?id=4').then(function (response) {
            //
            //     alert(response.data.name)
            //     vm.name = response.data.name;
            // }).catch(function (error) {
            //     alert(error)
            // })


            this.axios.get('http://localhost:8090/findStudentById?id=4').then(response =>{
                alert(response.data.name)
                this.name = response.data.name;
            }).catch(function (error) {
                alert(error)
            })


            // 传递参数
            // var vm = this;
            // this.axios({
            //     url:'http://localhost:8090/findStudentById',
            //     method:'get',
            //     params:{
            //         id:4
            //     }
            // }).then(function (response) {
            //
            //     alert(response.data.name)
            //     vm.name = response.data.name;
            // }).catch(function (error) {
            //     alert(error)
            // })

2、axios.post

axiosByPost:function () {
            // var vm = this;
            // var  param = new URLSearchParams();
            // param.append('id',4);
            // this.axios.post('http://localhost:8090/findStudentById',param).then(function (response) {
            //
            //     alert(response.data.name)
            //     vm.name = response.data.name;
            // }).catch(function (error) {
            //     alert(error)
            // })



            // var vm = this;
            // this.axios({
            //     url:'http://localhost:8090/findStudentById',
            //     method:'post',
            //         params:{
            //             id:4
            //         }
            // }).then(function (response) {
            //         alert(response.data.name)
            //         vm.name = response.data.name;
            // }).catch(function (error) {
            //     alert(error)
            // })
        }

3、.axios({})

 var vm = this;
            this.axios({
                url:'http://localhost:8090/findStudentById',
                method:'post', // post 或者 get
                    params:{
                        id:4
                    }
            }).then(function (response) {
                    alert(response.data.name)
                    vm.name = response.data.name;
            }).catch(function (error) {
                alert(error)
            })

spingboot 解决跨域问题

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CrossConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
}

以上是关于Vue工程化搭建的主要内容,如果未能解决你的问题,请参考以下文章

Vue2+ThreeJS工程无痛搭建指南

Vue2+ThreeJS工程无痛搭建指南

Vite2+Vue3+TypeScript:搭建企业级轻量框架实践

Vue工程化搭建

Vue工程化搭建

vue+webpack工程环境搭建