自己实现一个vue插件第一步
Posted qq_27449993
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自己实现一个vue插件第一步相关的知识,希望对你有一定的参考价值。
通过rollup打包vue.js插件,上一篇文章讲解了怎么通过rollup打包一个js库
rollup打包项目_qq_27449993的博客-CSDN博客
vue是mvvm结构,
- M (model):模型对象:指的是构成界面内容的相关数据
- V(view): view: 视图对象:指的是给用户或者开发者展示数据的界面
- VM(viewmodel): 视图模型对象:是view与model之间的桥梁
Vue.js的核心ViewModel
ViewModel是Vue.js的核心,它是一个Vue实例。Vue实例是作用于某一个html元素上的,这个元素可以是HTML的body元素,也可以是指定了id的某个元素。
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, viewport-fit=cover" />
<title>
vue-rollup打包项目第一步
</title>
</head>
<body>
<div id="app">
Vue
</div>
<script language="javascript" type="text/javascript" src="../dist/vue.js" ></script>
<script>
let vm=new Vue(
el:'#app',
data:
)
</script>
</body>
</html>
初始化vue
初始化init,采用文件模块化实现,针对initMixin的混入
打包后
(function (global, factory)
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Vue = factory());
)(this, (function () 'use strict';
function initMixin(Vue)
Vue.prototype._init = function (option)
this.$option = option;
;
function Vue(option)
this._init(option);
console.log(initMixin);
initMixin(Vue);
return Vue;
));
根据data,进行监听
首先判断data是否是一个函数,是的话,执行函数,再根据data判断是否是对象,data必须是一个对象,否则return
再根据data,进行监听
先写一个简易版的监听,只监听了data的第一层
utils/index.js
export const isFunction = function(obj)
return Object.prototype.toString.call(obj) === '[object Function]'
export const isObject=function(obj)
return Object.prototype.toString.call(obj) == '[object Object]'
observe/index
import isObject from '../utils/index'
export default function observe(data)
if(!isObject(data))
return
return new Observe(data)
function Observe(data)
Object.keys(data).forEach(key=>
console.log(data,key,data[key])
defineReactive(data,key,data[key])
)
function defineReactive(data,key,value)
let newValue=undefined
Object.defineProperty(data,key,
enumerable: true,
configurable: true,
get()
return newValue||value
,
set(value)
observe(value)
newValue=value
return value
)
将其写成一个class
import isObject from '../utils/index'
class Observe
constructor(data)
this.walk(data)
walk(data)
Object.keys(data).forEach(key=>
defineReactive(data,key,data[key])
)
function defineReactive(data,key,value)
Object.defineProperty(data,key,
get ()
return value
,
set(newVlaue)
observe(newVlaue)
value= newVlaue
)
export default function observe(data)
if(!isObject(data))
return
new Observe(data)
即初版针对data的监听就好了
以上是关于自己实现一个vue插件第一步的主要内容,如果未能解决你的问题,请参考以下文章
python——一步步教你用pyganme完成贪吃蛇小游戏(简易初版)