前端框架系列之(vue-class-component)

本文介绍了如何在Vue中实现类组件,并详细解析了利用装饰器转换类组件的过程。从创建Vue项目开始,逐步展示类组件的创建思路、装饰器的编写和使用,最终实现动态获取参数并转换成data函数的功能。

简介:

说到函数式组件跟类组件在react官方就有提供,具体差异的话大家可以自行查阅react开发文档,下面我们看一下在react中怎么使用这两种方式定义组件:

函数式组件:

function Welcome (props) {
   
   
  return <h1>Welcome {
   
   props.name}</h1>
}

类组件:

class Welcome extends React.Component {
   
   
  render() {
   
   
    return (
      <h1>Welcome {
   
    this.props.name }</h1>
    );
  }
}

在vue中注册组件想必大家应该也很容易实现,比如:

welcome.js:

export default {
   
   
	name: "welcome",
	render(h){
   
   
		return h('div','hello world!');
	}
}

那如果我们也需要在vue中使用类组件的话,比如:

export default class Welcome extends Vue{
   
   
  name="welcome";
	render(h){
   
   
		return h('div','hello world!');
	}
}

该怎么做呢? 接下来我们就一步一步实现一下。

实现:

创建工程:

我们就直接使用vue做demo了,所以我们第一步就是搭建一个简单的vue项目vue-class-component-demo:

vue-class-component-demo
	demo
  	index.html //页面入口文件
	lib
  	main.js //webpack打包过后的文件
	src
  	view
    	demo.vue //demo组件
		main.js //应用入口文件
	babel.config.js //babel配置文件
	package.json //项目清单文件
	webpack.config.js //webpack配置文件

index.html:

我们直接引用打包过后的文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="app"></div>
    <script src="http://127.0.0.1:8081/main.js"></script>
</body>
</html>

demo.vue:

<template>
    <div>hello world</div>
</template>
<script>
export default {
   
   
    name: "demo"
}
</script>

main.js:

加载demo.vue组件,挂在到“#app”元素上

import Vue from "vue";
import Demo from "./view/demo.vue";
new Vue({
   
   
    render(h){
   
   
        return h(Demo);
    }
}).$mount("#app");

babel.config.js:

babel的配置跟上一节的是一样的,大家感兴趣可以去看一下前端框架系列之(装饰器Decorator

module.exports = {
   
   
    "presets": [
        ["@babel/env", {
   
   "modules": false}]
    ],
    "plugins": [
        ["@babel/p
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值