Vue(五) Vue整合第三方工具

news/2024/7/5 3:44:42

一.Vue整合elementUI快速开发

        elementUI是饿了么团队开发的一套开源的基于Vue的前端框架,提供了很多现成可复用的组件库、布局库、动画库,方便我们使用Vue快速集成,快速开发一个完整、好看的前端页面。官方参考文档:Element - The world's most popular Vue UI framework

1.安装elementUI

        推荐使用 npm 的方式安装,它能更好地和 webpack 打包工具配合使用。elementUI组件会被安装到当前项目的依赖库下。

npm i element-ui -S

2.引入elementUI

        在main.js中引入全局elementUI组件和样式,并在Vue脚手架中注册使用。注意:此处是引入了完整的 Element。也可以按需引入相关组件,请参考官方文档。

import Vue from 'vue'
import App from './App'
import router from './router'
//引入element-ui组件和样式
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

//设置为 false ,可以阻止生产环境下 vue 在启动时生成生产提示
Vue.config.productionTip = false
//注册elementUI组件
Vue.use(ElementUI);

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

 3.使用elementUI组件

        引入全局elementUI之后,就可以在任何布局中使用elementUI提供的组件库,组件均以<el-xxx>开头,并提供了很多可选属性,方便我们进行自定义开发。(以Button为例)

<template>
  <div>
    <!--使用默认按钮组件-->
    <el-row>
      <el-button>默认按钮</el-button>
      <el-button type="primary">主要按钮</el-button>
      <el-button type="success">成功按钮</el-button>
      <el-button type="info">信息按钮</el-button>
      <el-button type="warning">警告按钮</el-button>
      <el-button type="danger">危险按钮</el-button>
    </el-row>
    <br>
    <!--使用简化按钮组件-->
    <el-row>
      <el-button plain>朴素按钮</el-button>
      <el-button type="primary" plain>主要按钮</el-button>
      <el-button type="success" plain>成功按钮</el-button>
      <el-button type="info" plain>信息按钮</el-button>
      <el-button type="warning" plain>警告按钮</el-button>
      <el-button type="danger" plain>危险按钮</el-button>
    </el-row>
    <br>
    <!--使用圆角按钮组件-->
    <el-row>
      <el-button round>圆角按钮</el-button>
      <el-button type="primary" round>主要按钮</el-button>
      <el-button type="success" round>成功按钮</el-button>
      <el-button type="info" round>信息按钮</el-button>
      <el-button type="warning" round>警告按钮</el-button>
      <el-button type="danger" round>危险按钮</el-button>
    </el-row>
    <br>
    <!--使用图标按钮-->
    <el-row>
      <el-button icon="el-icon-search" circle></el-button>
      <el-button type="primary" icon="el-icon-edit" circle></el-button>
      <el-button type="success" icon="el-icon-check" circle></el-button>
      <el-button type="info" icon="el-icon-message" circle></el-button>
      <el-button type="warning" icon="el-icon-star-off" circle></el-button>
      <el-button type="danger" icon="el-icon-delete" circle></el-button>
    </el-row>
  </div>
</template>

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

<style scoped>

</style>

总结:

  • 在elementUI中所有组件的属性全部写在组件标签上  
  • 在elementUI中所有组件都是 <el-组件名称> 方式进行命名

  • 在elementUI中组件的属性使用,都是直接将[属性名=属性值]方式写在对应的组件标签上。如果是布尔类型的属性,可以只写标签标识默认值。

4.主要组件介绍(如何使用官方文档)

(1)Button组件

参数说明类型可选值默认值
size尺寸stringmedium / small / mini
type类型stringprimary / success / warning / danger / info / text
plain是否朴素按钮booleanfalse
round是否圆角按钮booleanfalse
circle是否圆形按钮booleanfalse
loading是否加载中状态booleanfalse
disabled是否禁用状态booleanfalse
icon图标类名string
autofocus是否默认聚焦booleanfalse
native-type原生 type 属性stringbutton / submit / resetbutton
<template>
  <div>
    <!--基础用法-->
    <el-row>
      <el-button type="success" plain icon="el-icon-loading">等待按钮</el-button>
      <el-button type="primary" plain icon="el-icon-eleme" disabled>禁用按钮</el-button>
    </el-row>
    <br>
    <!--图标文字组合按钮-->
    <el-row>
      <el-button type="primary" icon="el-icon-delete"></el-button>
      <!--图标默认在文字左侧-->
      <el-button type="primary" icon="el-icon-search">搜索</el-button>
      <!--改变图标文字相对位置 <i>标签中class声明图标-->
      <el-button type="primary">上传<i class="el-icon-upload el-icon--right"></i></el-button>
    </el-row>
    <br>
    <!--按钮组-->
    <el-button-group>
      <el-button type="primary" icon="el-icon-arrow-left">上一页</el-button>
      <el-button type="primary">下一页<i class="el-icon-arrow-right el-icon--right"></i></el-button>
    </el-button-group>
  </div>
</template>

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

<style scoped>

</style>

二.Vue整合MarkDown编辑器

        常见的编辑器主要有MarkDown编辑器和富文本编辑器。Markdown 是一种轻量级标记语言,它允许人们使用易读易写的纯文本格式编写文档。在Vue前端整合MarkDown编辑器时,我们选择支持Vue且比较好用的mavon-editot插件(维护地址:GitHub - hinesboy/mavonEditor: mavonEditor - A markdown editor based on Vue that supports a variety of personalized features)

1.安装mavon-editor

在Vue项目根目录下,运行指令:npm install mavon-editor --save

2.全局注册mavon-editor组件 

在项目 main.js 中,引入如下代码:

//1.引入mavon-editor编辑插件+css样式
import mavonEditor from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
//2.注册使用mavonEditor组件
Vue.use(mavonEditor)

 3.使用mavon-editor组件

(1)使用:引入并注册mavon-editor组件后,在任意界面都可以直接使用 <mavon-editor></mavon-editor> 标签引入编辑器。

<template>
  <div>
    <!--elementUI 表单样式-->
    <el-form ref="form" :model="sizeForm" label-width="80px" size="mini">

      <el-form-item label="内容" prop="content">
        <!--导入markdown组件,绑定editContent属性来获取输入内容-->
        <mavon-editor v-model="editContent"/>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm()">立即创建</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "Edit",
  data(){
    return{
      editContent: ''
    }
  },
  methods:{
    submitForm(){
      //显示编辑器内容,看看编辑器提交的都是些什么东西
      console.log(this.editContent)
    }
  }
}
</script>

(2)内容:我们通过点击事件可以看到,mavon-editor绑定的内容其实就是markdown格式的标记语言!所以以后如果想要将内容显示回markdown,就要使用相应的markwodn格式解析插件来对内容进行回显!

 

 4.上传图片设置

        原始的markdown插件直接上传图片,图片的访问地址url是一个简单的图片名称。在解析markdown标记语言时,图片是无法进行回显的。所以我们需要对上传图片做一些设置,其思路如下:

  • 前端整合markdown上传/添加图片时,触发图片上传事件,将图片上传到后端服务器
  • 后端服务器接收图片对象,将图片存储到本地资源文件目录下,并向前端返回图片的可访问url地址
  • 前端接收后端返回的图片的url地址,并回显替换掉markdown编辑器内容中的图片地址
  • 在解析和回显markdown标记语言时,可以直接访问内容中的图片的可访问url,直接显示图片

(1)前端代码

<template>
  <div>
    <el-form ref="form" :model="sizeForm" label-width="80px" size="mini">
      <el-form-item label="内容" prop="content">
        <!--导入markdown组件
              1.v-model 绑定editContent属性来获取输入内容
              2.ref 设置引用名称,用于vue直接调用页面dom元素及其子元素(此处用于修改图片url)
              3.@imgAdd mavon-editor内置图片添加回调事件(filename: 写在md中的文件名, File: File Object)
        -->
        <mavon-editor ref="md" v-model="editContent" @imgAdd="imgAdd"/>
        <!--
          ref:被用来给元素或子组件注册引用信息, 引用信息将会注册在父组件的 $refs 对象上,如果是在普通的DOM元素上使用,引用指向的就是 DOM 元素,如果是在子组件上,引用就指向组件的实例。
          $refs: $refs是Vue的一个对象,持有已注册过 ref 的所有的子组件。
          注意:
            ref 需要在dom渲染完成后才会有,在使用的时候确保dom已经渲染完成。比如在生命周期mounted(){}钩子中调用
            ref主要是用于在Vue中简化dom节点操作,document.querySelector("xxx")
        -->
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm()">立即创建</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: "Edit",
  data(){
    return{
      editContent: ''
    }
  },
  methods:{
    submitForm(){
      console.log(this.editContent)
    },
    // 将图片上传到服务器,返回地址替换到md中
    imgAdd(pos,file){
      //1.创建表单数据对象(传递图片)
      let formData = new FormData();
      formData.append("file",file);
      //2.发送请求(两种方式)
      //  - axios(config)方式,默认为get请求
      //  - axios.post(url,data,config)方式,对上一种方法的简化(为方便起见,为所有支持的请求方法提供了别名)
      //方式一
      axios({
        url: 'http://localhost:8080/blog/uploadImg',
        method: 'post',
        data: formData,
        headers: {'Content-Type': 'multipart/form-data'}
      }).then(res=>{
        // 3.将返回的url替换到文本原位置![...](0) -> ![...](url)
        //  $vm指为mavonEditor实例,可以通过如下两种方式获取
        //  (1)通过引入对象获取: import {mavonEditor} from ... 等方式引入后,此时$vm即为mavonEditor
        //  (2)通过$refs获取: html声明ref : <mavon-editor ref=md ></mavon-editor>, 此时$vm为 this.$refs.md
        //  (3)$img2Url是mavon-editor内置的 图片url属性,我们需要修改这个dom来修改返回的url地址!
        console.log(res);
        this.$refs.md.$img2Url(pos,res.data);
      }).catch(err=>{
        console.log(err);
      });
      //方式二
      // let config = {
      //   headers: {'Content-Type': 'multipart/form-data'}
      // };
      // axios.post('http://localhost:8080/blog/uploadImg',formData,config).then(res => {
      //   this.$refs.md.$img2Url(pos,res.data);
      // }).catch(err=>{
      //   console.log(err);
      // });
    }
  }
}
</script>

<style scoped>

</style>

 (2)后端yml配置

#资源文件存储位置
file:
  resource:
    #真实存储位置
    realpath: D:/codes/resource/
    #资源访问路径
    visitpath: /file/

(3)静态资源访问映射 

        在存储图片时,我们是直接存储到本地的真实绝对路径下(realpath);但是在浏览器访问图片资源时,我们是不能直接访问服务器的绝对路径的。可以通过springboot的资源映射将虚拟资源访问路径映射到真实存储位置来间接的访问资源文件。

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${file.resource.realpath}")
    private String realPath;

    @Value("${file.resource.visitpath}")
    private String visitPath;

    //添加静态资源映射
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(visitPath+"**").addResourceLocations("file:"+realPath);
    }
}

 (4)后端图片上传处理逻辑

@Controller
@CrossOrigin
@RequestMapping("/blog")
public class BlogController {
    @Value("${file.resource.realpath}")
    private String realPath;

    @Value("${file.resource.visitpath}")
    private String visitPath;

    @RequestMapping("/uploadImg")
    @ResponseBody
    public String uploadImg(MultipartFile file, HttpServletRequest request){
        System.out.println(file.getOriginalFilename());
        //1.获取原始文件名称
        String originalFilename = file.getOriginalFilename();
        //2.获取文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //3.根据UUID构造唯一的新文件名称
        String newFileName = UUID.randomUUID() + suffix;
        //4.构造静态资源访问路径(返回图片访问路径) http://localhost:8080/file/imageName.PNG
        //  - getScheme():返回当前链接使用的协议
        //  - getServerName():返回当前页面所在的服务器的名字
        //  - getServerPort():返回当前页面所在的服务器使用的端口
        //  - getContextPath():返回当前页面所在的应用的名字
        String ImgUrl = request.getScheme()
                    + "://"
                    + request.getServerName()
                    + ":"
                    + request.getServerPort()
                    + request.getContextPath()
                    + visitPath + newFileName;
        //存储文件到目标目录
        try {
            file.transferTo(new File(realPath,newFileName));
            return ImgUrl;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "图片上传失败,请重新上传!";
    }
}

(5)效果 

三.Vue整合MarkDown解析器 

        在上节对MarkDown编辑内容进行存储后,我们需要在用户访问时进行MarkDown标记语言的解析回显。在这里我们需要用到两个插件:

  • markdown-it:该插件用于解析markdown标记语言,将其中的markdown语法转换为HTML元素,便于文章内容回显。
  • github-markdown-css:该插件是markdown的样式渲染

 1.下载安装插件

# 用于解析md文档
npm install markdown-it --save
# md样式
npm install github-markdown-css

2. 后端测试接口

@Controller
@CrossOrigin
@RequestMapping("/blog")
public class BlogController {

    @RequestMapping("/getBlog")
    @ResponseBody
    public Blog getBlog(){
        Blog blog = new Blog();
        blog.setTitle("MarkDown文章内容回显测试");
        //设置测试的markdown格式内容
        blog.setContent("**加粗**\n" +
                "    *斜体*\n" +
                "    ***斜体加粗***\n" +
                "    ~~删除线~~\n" +
                "![图片描述](https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2Ftp09%2F21052112102250D-0-lp.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1643515801&t=f802ca20d9757c620f4cd81deb90bccc)");
        //System.out.println(blog);
        return blog;
    }
}

3.前端页面

  • markdown-it使用:通过require导入执行markdown-it模块,使用render函数渲染文章内容
  • markdown-css使用:通过import导入css样式,在页面中通过markdown-body渲染样式
<template>
  <div>
    <h2>{{blog.title}}</h2>
    <!--使用markdown.css样式展示渲染后的markdown格式内容-->
    <div class="content markdown-body" v-html="blog.content"></div>
  </div>
</template>

<script>
import 'github-markdown-css/github-markdown.css'
import axios from 'axios'
export default {
  name: "BlogDetail",
  data(){
    return{
      blog:{
        title: "",
        content: ""
      }
    }
  },
  methods: {
    getBlog(){
      axios.get('http://localhost:8080/blog/getBlog').then(res=>{
        //console.log(res);
        //1.获取后端的blog对象
        this.blog = res.data;
        //2.使用markdown-it渲染/解析markdown语法(渲染上html元素)
        var md = require('markdown-it')();
        var result = md.render(this.blog.content);
        this.blog.content = result;
        //console.log(this.blog.content)
        //3.在页面中使用markdown样式+v-html标签显示即可
      });
    }
  },
  created() {
    this.getBlog();
  }
}
</script>

<style scoped>

</style>


http://www.niftyadmin.cn/n/4423129.html

相关文章

C++(一) 进阶知识(类、结构体、预处理命令)一文通

一.类的基本概念 类是一些列属性数据和事务行为的封装&#xff0c;是C面向对象的核心基础。类是对象的抽象&#xff0c;对象是类的具体化&#xff1b;类的基本内容包括事物的属性&#xff08;静态数据字段&#xff09;和行为&#xff08;动态函数方法&#xff09;&#xff0c;类…

利用SQL Server的扩展属性象access一样显示列的注释

利用SQL Server的扩展属性象access一样显示列的注释 access的设计视图有个不错的功能-----设计列的注释&#xff0c;这可以让设计者清楚地看到每个列的意义。一般的sql server建表时没有这个功能&#xff0c;但是他有扩展属性&#xff0c;这个功能也不错&#xff0c;可以把注释…

C#(一) C# 基础语法一文通

C# 是由微软&#xff08;Microsoft&#xff09;开发的&#xff0c;基于C和C的一种面向对象的编程语言&#xff0c;其语法规则十分类似于Java&#xff0c;常用于快速开发Windows桌面应用。本文将对C# 的一些基础语法知识进行快速学习&#xff0c;快速上手。 一.C# 程序结构 usi…

WinForm(一) WinForm入门与基本控件使用

一.Winform入门 WinForm 是 Windows Form 的简称&#xff0c;是基于 .NET Framework 平台的客户端&#xff08;PC软件&#xff09;开发技术&#xff0c;一般使用 C# 编程。在VS2019中&#xff0c;C# WinForm 编程需要创建「Windows窗体应用程序」项目。Windows 窗体应用程序是 …

WinForm(二) WinForm进阶与复杂控件使用

一.复合控件 1.控件的使用综述&#xff1a;在WinForm中使用控件主要包括以下几种情况&#xff08;1&#xff09;标准控件&#xff1a;直接使用winform自带的控件&#xff0c;比如button、textBox等。我们只需要修改属性&#xff0c;添加事件即可。&#xff08;2&#xff09;复合…

canal番外篇-otter

前置知识点 主从复制binlogcanal正则dockerjava 前置工具 dockerotter-all 场景描述&#xff08;增量同步&#xff09; 目前项目中使用的是mysql5.5&#xff0c;计划升级为mysql8.1&#xff0c;版本跨度较大&#xff0c;市面上可靠工具选择较少。otter符合预期&#xff0c…

显示表结构描述的Sql语句

select column_name,data_type,column_default,character_maximum_length from information_schema.columns where table_namet_conclusion select objname,value from ::fn_listextendedproperty(default,user,dbo,table,t_conclusion,column,default)

深度学习(一) Python基本科学计算库

一.Numpy NumPy(Numerical Python) 是 Python 语言的一个扩展程序库&#xff0c;支持大量的维度数组与矩阵运算&#xff0c;此外也针对数组运算提供大量的数学函数库。其基本运算对象是一个N维数组对象 ndarray。 - 导入Numpy&#xff1a;import numpy as np 1.ndarray 数组初始…