一.Vue的插件在一个页面里的使用
- 这样子基本上没有太大的效率
- 无法重复利用,没起到封装的作用
<!DOCTYPE html>
<html lang="en">
<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">
<title>第三方插件</title>
</head>
<body>
<div id="app">
<h2 v-text='msg'></h2>
<h2 v-upper-text="msg"></h2>
<h2 v-lower-text="msg"></h2>
</div>
</body>
<script src="https://juejin.cn/js/vue.js"></script>
<script>
Vue.config.productionTip = false;
//2.应该在new实例对象之前就讲属性添加到vm实例对象上去
//像Vue的原型上添加一个$now属性,值为当前时间,$now是给vm用的
Vue.prototype.$now = Date.now(); //放的是毫秒数进去
// Vue.prototype.$now = new Date().toLocaleString(); //2021/7/5下午9:26:06
Vue.prototype.$now = new Date().toTimeString(); //21:27:09 GMT+0800 (中国标准时间)
// 3.定义一个全局指令:-upper-text
Vue.directive('upper-text', function (el, binding) {
// console.log(el); //实体DOM
// console.log(binding); //虚拟DOM
el.innerText = binding.value.toUpperCase();
})
// 4.向Vue添加一些东西
Vue.showInfo = function () {
console.log("展示一下信息");
}
const vm = new Vue({
el: "#app",
data() {
return {
msg: "helloWorld",
}
},
})
//1.当往这里的vm对象加上$now时,vm实例对象已经解析完毕,晚了;应该在vm实例的原型上添加才可以
// vm.$now = Date.now();
</script>
</html>
复制代码
二.封装plugin的JS页面
- 封装的Vue插件可以重复利用
<!DOCTYPE html>
<html lang="en">
<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">
<title>第三方插件</title>
</head>
<body>
<div id="app">
<h2 v-text='msg'></h2>
<h2 v-upper-text="msg"></h2>
<h2 v-lower-text="msg"></h2>
<h2>此时的时间的毫秒数是:{{$now1}}</h2>
<h2>此时的时间是:{{$now2}}</h2>
<h2>此时的时间是:{{$now3}}</h2>
<h2>调用[2,8)之间的随机整数:{{$random(2,8)}}</h2>
</div>
</body>
<script src="https://juejin.cn/js/vue.js"></script>
<script src="https://juejin.cn/post/atguigu.js"></script>
<script>
Vue.config.productionTip = false;
// 1.这样直接调用没什么用
// atguigu.install(100, 200)
// 2.使用use()方法,Vue帮我们调用
Vue.use(atguigu);
console.log(Vue.projectName);
console.log(Vue.version);
Vue.showInfo()
const vm = new Vue({
el: "#app",
data() {
return {
msg: "helloWorld",
}
},
})
</script>
</html>
复制代码
/*
Vue中插件的定义就是一个包含install方法的对象
*/
const atguigu={};
atguigu.install=function(Vue,options){//Vue,配置项
// console.log(Vue,options);
// 1.添加两个全局指令
// 1.1 定义一个转换大写全局指令
Vue.directive('upper-text',function(el,binding){
// console.log(el,binding);
el.innerText=binding.value.toUpperCase();
})
// 1.2 定义一个转换小写全局指令
Vue.directive('lower-text',function(el,binding){
el.innerText=binding.value.toLowerCase();
})
// 2.给Vue添加一些属性
Vue.projectName="superMall";
Vue.version="v1.0";
Vue.showInfo=function(){
console.log("展示一些信息");
}
// 3.在Vue的原型上添加一个$now1属性
Vue.prototype.$now1=Date.now();
Vue.prototype.$now2=new Date().toLocaleString();
Vue.prototype.$now3=new Date().toTimeString();
// 4.在Vue的原型上添加一个$random的方法
Vue.prototype.$random=function(min,max){//[2,8)
return Math.floor(Math.random()*(max-min))+min
}
}
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END