原生JS转Vue格式的思路

最近用Vue 转写原生js 的代码遇到很多坑,但是只要转变思路,很多问题就能迎刃而解。这里不妨借鉴C++中类的概念:

  1. 在类结构中声明公共变量和公共对象;
  2. 在类的构造函数中初始化这些变量和对象;
  3. 类中的各种函数可以供自身其他函数调用,但是主要是供外部调用。

将这个思路带入Vue中,就是这样的做法:

  1. 在data区声明需要多次用到的对象;
  2. mounted区中初始化这些对象;
  3. methods区中的各种方法可以被其他方法调用,但主要供HTML元素触发使用。

实例

HTML代码

首先来看这段代码,通过两个按钮触发改变div颜色的函数。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			#box1{
				height: 300px;
				width: 300px;
				background-color: aquamarine;
			}
		</style>
	</head>
	<body>
		<div id='box1'></div>
		<hr >
		<button type="button" onclick="fillGreen()">填充绿色</button>
		<button type="button" onclick="fillBlue()">填充蓝色</button>
		
		<script type="text/javascript">
			boxStyle=document.getElementById('box1').style
			
			function fillGreen(){
				boxStyle.backgroundColor='green'
			}
			
			function fillBlue(){
				boxStyle.backgroundColor='blue'
			}
			
		</script>
		
	</body>
</html>

在这里插入图片描述

代码分析

这段代码实现了两个功能,即分别将box的颜色设置为蓝色或绿色。在这两个方法中,都用到了对象boxStyle。boxStyle这个对象在程序运行即被初始化。

转写成Vue组件
<template>
  <div id="box1"></div>
  <hr />
  <button type="button" @click="fillGreen()">填充绿色</button>
  <button type="button" @click="fillBlue()">填充蓝色</button>
</template>
<style scoped>
#box1 {
  height: 300px;
  width: 300px;
  background-color: aquamarine;
}
</style>
<script>
export default {
  data() {
    return {
      boxStyle: {},
    };
  },
  mounted() {
    this.boxStyle = document.getElementById("box1").style;
  },
  methods: {
    fillGreen() {
      this.boxStyle.backgroundColor = "green";
    },
    fillBlue() {
      this.boxStyle.backgroundColor = "blue";
    },
  },
};
</script>
  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

高堂明镜悲白发

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值