组件间通信的几种方式

1.父子组件通信:

1)通过props传递值

父组件:

<b-map-component :msg="List"></b-map-component>

子组件:

props: ['msg']

和data中的数据用法一样

2)自定义事件($emit)

子组件中调用父组件中的方法

父组件:

<b-map-component v-on:fatherEmit = "fatherAdd"></b-map-component>
 methods: {
    fatherAdd(a){
        console.log(a,'hhhhhhhhhhhhhh')
	},
}

子组件:

this.$emit("fatherEmit",a)

3)ref

父组件可以通过ref给子组件打标识,一个父组件中用到了多个相同的子组件,用ref可以区分出具体哪个子组件,通过this.$refs.子组件的ref名,可以调用子组件中的方法

父组件:

<template>
  <div>
    <editor-bar
      v-model="content"
      @change="getEditor"
      ref="weditor1"
    ></editor-bar>
    <editor-bar
      v-model="content1"
      @change="getEditor1"
      ref="weditor2"
    ></editor-bar>
    <el-button @click="submit">提交</el-button>
  </div>
</template>
<script>
import EditorBar from "./editor";
import axios from "axios";
export default {
  components: {
    EditorBar
  },
  data() {
    return {
      content: "<p>111111111111111</p>",
      content1: "<p>22222222222</p>",
      myeditor: "<p>dfasdfasdfsad</p>"
    };
  },
  mounted(){
    this.$refs.weditor1.setText('<p>4444444444</p>')
    this.$refs.weditor2.setText('<p>66666666666666</p>')


  },
  methods: {
    getEditor(value) {
      console.log(value);
      this.content = value;
    },
    getEditor1(value) {
      console.log(value);
      this.content1 = value;
    },
    submit() {
      axios("/meun").then(req => {
        console.log("xxxxxxxxx", req);
      });
    }
  }
};
</script>

子组件

<template>
  <div :class="prefixCls">
    <div ref="editor" class="editor-wrapper"></div>
  </div>
</template>
 
<script>
import WEditor from "wangeditor";
 
export default {
  name: "WangEditor",
  props: {
    prefixCls: {
      type: String,
      default: "my-editor"
    },//class名称
    // eslint-disable-next-line
    value: {
      type: String,
      default: ""
    },
    isClear: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      editor: null,
      editorContent: null
    };
  },
  watch: {
    isClear(val) {
      // 触发清除文本域内容
      if (val) {
        this.editor.txt.clear();
        this.editorContent = null;
      }
    }
  },
  mounted() {
    this.initEditor();
  },
  methods: {
    getText() {
      this.editor.txt.text();
    },
    setText(val) {
      this.editor.txt.html(val);
    },
    initEditor() {
      this.editor = new WEditor(this.$refs.editor);
      // this.editor = new E(this.$refs.toolbar, this.$refs.editor)
      this.editor.config.uploadImgShowBase64 = true; // base 64 存储图片
      this.editor.config.showLinkImg = false;//关闭通过图片地址添加图片
      // this.editor.config.uploadImgServer =
      //   "/meun"; //如果需要本地上传图片 需配置上传图片服务器地址 找后端要
      // this.editor.config.uploadImgHeaders = {}; // 自定义 header
      // this.editor.config.uploadFileName = "file"; // 后端接受上传文件的参数名
      // this.editor.config.uploadImgMaxSize = 2 * 1024 * 1024; // 将图片大小限制为 2M
      // this.editor.config.uploadImgMaxLength = 6; // 限制一次最多上传 3 张图片
      // this.editor.config.uploadImgTimeout = 3 * 60 * 1000; // 设置超时时间
      // 配置菜单 可根据文档进行添加
      this.editor.config.menus = [
      "bold", // 粗体
      "fontSize", // 字号
      "fontName", // 字体
      "underline", // 下划线
      "strikeThrough", // 删除线
      "foreColor", // 文字颜色
      "backColor", // 背景颜色
      "justify", // 对齐方式
      "image", // 插入图片
      "undo", // 撤销
      "redo" // 重复
    ];
 
      this.editor.config.uploadImgHooks = {
        fail: (xhr, editor, result) => {
          // 插入图片失败回调
          console.log(xhr, editor, result);
        },
        success: (xhr, editor, result) => {
          // 图片上传成功回调
          console.log(xhr, editor, result);
        },
        timeout: (xhr, editor) => {
          // 网络超时的回调
          console.log(xhr, editor);
        },
        error: (xhr, editor) => {
          // 图片上传错误的回调
          console.log(xhr, editor);
        },
        customInsert: (insertImg, result, editor) => {
          // 图片上传成功,插入图片的回调
          // result为上传图片成功的时候返回的数据,这里我打印了一下发现后台返回的是result.data:[{"路径的形式"},...]
          // console.log('result.data[0].url', result.data[0].url)
          // insertImg()为插入图片的函数
          // 循环插入图片
          console.log(editor);
          for (let i = 0; i < 1; i++) {
            console.log("result", result); // 根据格式来赋值
            const src = result.url; // 如果返回的是完整的src就不用拼接 !!!!这里需要注意
            insertImg(src);
          }
        }
      };
      // 创建富文本编辑器
      this.editor.config.onchange = html => {
        // let str = html;
        // str = str.replace(/\bm.*?;/, "width:100px"); //更改插入到富文本里图片的宽度
        // this.editorContent = str;
        this.editorContent = html;
        this.$emit("change", this.editorContent); // 将内容同步到父组件中
      };
      // this.editor.config.zIndex = 2; // 配置富文本的权重 不然会覆盖其他组件
      this.editor.create();
    
    }
  }
};
</script>
 
<style lang="less" scoped>
.my-editor {
  .editor-wrapper {
    text-align: left;
  }
}
</style>
 

2.自定义指令

应用场景:按钮级权限控制   弹窗拖拽效果

(1)按钮级权限控制(思路:当没有权限时给其按钮删除掉)

1.新建一个btnPermissions.ts文件

export default (app: {
	directive: (
		arg0: string,
		arg1: {
			// 当被绑定的元素插入到 DOM 中时……
			mounted: (el: any, binding: any, vnode: any) => void
		}
	) => void
}) => {
	// 注册一个全局自定义指令 `v-auth`
	app.directive('auth', {
		// 当被绑定的元素插入到 DOM 中时……
		mounted(el, binding) {
			const value = binding.value
			const auths = localStorage.getItem('buttons') || ''
			if (!auths.split(',').includes(value)) {
				el.parentNode && el.parentNode.removeChild(el)
			}
		}
	})
}

参数解释
el:指令所绑定的元素,可以直接操作DOM。
binding:是一个对象,包含该指令的所有信息。binding.value,传递给指令的值,例如:<el-button v-auth="'chestExport'" >导出历史</el-button>,传递给auth指令的值就是'chestExport',我们可以拿到值判断是否在后端给的按钮权限列表中,再控制是否删除该DOM元素

2.在main.ts中注册为全局指令

import directives from '@/utils/btnPermissions'
directives(app)

3.在页面中使用

该按钮对应的和后端唯一标识是什么,这里就写什么

<el-button v-auth="'chestExport'" @click="clickExportLog">导出历史</el-button>

(2)弹窗拖拽效果效果实现

 1.新建drag.ts文件 实现拖拽部分的ts代码

/**
 * 拖拽移动
 * @param  {elementObjct} bar 鼠标点击控制拖拽的元素
 * @param {elementObjct}  target 移动的元素
 * @param {function}  callback 移动后的回调
 */
export function startDrag(bar, target, callback) {
	console.log('target', target)

	var params = {
		top: 0,
		left: 0,
		currentX: 0,
		currentY: 0,
		flag: false,
		cWidth: 0,
		cHeight: 0,
		tWidth: 0,
		tHeight: 0
	}

	// 给拖动块添加样式
	bar.style.cursor = 'move'

	// 获取相关CSS属性
	// o是移动对象
	// var getCss = function (o, key) {
	//   return o.currentStyle ? o.currentStyle[key] : document.defaultView.getComputedStyle(o, false)[key];
	// };

	bar.onmousedown = function (event) {
		// 按下时初始化params
		var e = event ? event : window.event
		params = {
			top: target.offsetTop,
			left: target.offsetLeft,
			currentX: e.clientX,
			currentY: e.clientY,
			flag: true,
			cWidth: document.body.clientWidth,
			cHeight: document.body.clientHeight,
			tWidth: target.offsetWidth,
			tHeight: target.offsetHeight
		}

		// 给被拖动块初始化样式
		target.style.margin = 0
		target.style.top = params.top + 'px'
		target.style.left = params.left + 'px'

		if (!event) {
			// 防止IE文字选中
			bar.onselectstart = function () {
				return false
			}
		}

		document.onmousemove = function (event) {
			// 防止文字选中
			window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty()

			var e = event ? event : window.event
			if (params.flag) {
				var nowX = e.clientX
				var nowY = e.clientY
				// 差异距离
				var disX = nowX - params.currentX
				var disY = nowY - params.currentY
				// 最终移动位置
				var zLeft = 0
				var zTop = 0

				zLeft = parseInt(params.left) + disX
				// 限制X轴范围
				if (zLeft <= -parseInt(params.tWidth / 2)) {
					zLeft = -parseInt(params.tWidth / 2)
				}
				if (zLeft >= params.cWidth - parseInt(params.tWidth * 0.5)) {
					zLeft = params.cWidth - parseInt(params.tWidth * 0.5)
				}

				zTop = parseInt(params.top) + disY
				// 限制Y轴范围
				if (zTop <= 0) {
					zTop = 0
				}
				if (zTop >= params.cHeight - parseInt(params.tHeight * 0.5)) {
					zTop = params.cHeight - parseInt(params.tHeight * 0.5)
				}

				// 执行移动
				target.style.left = zLeft + 'px'
				target.style.top = zTop + 'px'
			}

			if (typeof callback == 'function') {
				callback(zLeft, zTop)
			}
		}

		document.onmouseup = function () {
			params.flag = false
			document.onmousemove = null
			document.onmouseup = null
		}
	}
}

2.新建directive.ts文件 注册指令

// 引入拖拽js
import { startDrag } from './drag.js'

/**
 * 为el-dialog弹框增加拖拽功能
 * @param {*} el 指定dom
 * @param {*} binding 绑定对象
 * desc   只要用到了el-dialog的组件,都可以通过增加v-draggable属性变为可拖拽的弹框
 */
const draggable = (el, binding) => {
	// 绑定拖拽事件 [绑定拖拽触发元素为整个弹框、拖拽移动元素为整个弹框]
	startDrag(el.querySelector('.el-dialog'), el.querySelector('.el-dialog'), binding.value)
}

const directives = {
	draggable
}
// 这种写法可以批量注册指令
export default {
	install(Vue) {
		Object.keys(directives).forEach((key) => {
			Vue.directive(key, directives[key])
		})
	}
}

querySelector用于查询页面中第一个符合规则的元素 ,Element实例调用是获取该元素子树内匹配的元素。

3.main.ts文件中全局引入vue指令

import directive from '@/utils/directive'
app.use(store).use(router).use(HyForm).use(directive).mount('#app')

4.页面中使用

 

<div class="grade-main" v-draggable>
		<el-dialog
			v-model="show"
			width="80%"
			title="ISS-AIS评分"
			:show-close="false"
			:close-on-click-modal="false"
			:close-on-press-escape="false"
		>
        </el-dialog>
</div>

注意这里要写到el-dialog的外层标签上 否则找不到该元素 

vue3的props与emit在语法糖与非语法糖中的使用_xyz_road的博客-CSDN博客

https://blog.csdn.net/xyz_road/article/details/123073296

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值