一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第23天,点击查看活动详情。
使用 dayjs
bootcdn 是全球最受欢迎的前端组件库,用于开发响应式布局、移动设备优先的 WEB 项目,我们 在页面搜索 day.js,复制链接,在浏览器打开,右键另存为下载下来,放到项目中
我们还可以在页面打开 github 查看用法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue初识</title>
<script type="text/javascript" src="./js/vue.js"></script>
<script type="text/javascript" src="./js/dayjs.min.js"></script>
</head>
<body>
<div id="root">
<!--计算属性实现-->
<h2>现在时间是:{{fmtTime}}</h2>
<!--methods实现-->
<h2>现在时间是:{{getFmtTime()}}</h2>
<!--过滤器实现(传参)-->
<h2>现在时间是:{{time | timeFormater('YYYY年MM月DD日 HH:mm:ss') | mySlice}}</h2>
</div>
<div id="root2">
<h2>{{msg | mySlice}}</h2>
<h2 :x="msg | mySlice">Hello world</h2>
</div>
<script type="text/javascript">
Vue.config.productionTip = false
//全局过滤器
Vue.filter('mySlice',function (value) {
return value.slice(0,5)
})
//创建vue实例
new Vue({
el: "#root",
data: {
time:1648430790000
},
computed:{
fmtTime(){
return dayjs(this.time).format('YYYY-MM-DD HH:mm:ss')
}
},
methods:{
getFmtTime(){
return dayjs(this.time).format('YYYY-MM-DD HH:mm:ss')
}
},//局部过滤器
filters:{
timeFormater(value,str='YYYY-MM-DD HH:mm:ss'){
return dayjs(value).format(str)
}
}
})
new Vue({
el: "#root2",
data: {
msg:"hello world"
}
})
</script>
</body>
</html>
过滤器
过滤器
定义:对要显示的数据进行特定格式化后再显示(适用于一些简单逻辑的处理)
语法:
1.注册过滤器:Vue.filter(name,callback)或new Vue{filters:{}}
2.使用过滤器:{{ xxx│过滤器名}}或v-bind:属性= “xxx│过滤器名"
备注:
1.过滤器也可以接收额外参数、多个过滤器也可以串联
2.并没有改变原本的数据,是产生新的对应的数据
插件
功能:用于增强 Vue 本质:包含 install 方法的一个对象,install 的第一个参数是 Vue,第二个以后的参数是插件使用者传递的数据 定义插件:
对象.install = function(Vue,options){
//1.添加全局过滤器
vue.filter(...)
//2.添加全局指令
Vue.directive(...)
//3.配置全局混入(合)
Vue.mixin(...)
//4.添加实例方法
Vue.prototype.$myMethod = function(){}
Vue.prototype.$myProperty = xxx
}
使用插件:Vue.use()
我们着手写一个插件,跟 main.js 同级,新增一个 plugins.js
//完整写法
/*
const obj = {
install(){
console.log("install");
}
}
export default obj*/
//简写
export default {
install(Vue,x,y) {
console.log(x,y)
//全局过滤器
Vue.filter('mySlice', function (value) {
return value.slice(0, 4)
})
//定义全局指令
Vue.directive('fbind', {
bind(element, binding) {
element.value = binding.value
},
inserted(element, binding) {
element.focus()
},
update(element, binding) {
element.value = binding.value
}
})
//定义混入
Vue.mixin({
data() {
return {
x: 100,
y: 200
}
}
})
//给Vue原型上添加一个方法(vm和vc就都能用了)
Vue.prototype.hello = ()=>{alert("hello")}
}
}
然后在 main.js 中使用插件
//引入Vue
import Vue from 'vue';
//引入App
import App from './App';
//引入插件
import plugins from "@/plugins";
//关闭vue的生产提示
Vue.config.productionTip = false
//使用插件
//Vue.use(plugins)
//使用插件 并传参数
Vue.use(plugins,1,2)
//创建vm
new Vue({
el: "#app",
render: h => h(App)
})
在 Student.vue 中测试
<template>
<div>
<h2>学生姓名:{{ name|mySlice }}</h2>
<h2>学生性别:{{ sex }}</h2>
<input type="text" v-fbind:value="name"><br><br>
<button @click="test">点我测试 hello 方法</button>
</div>
</template>
<script>
export default {
name: "Student",
data() {
return {
name: "张三12345",
sex: "男",
}
},
methods: {
test() {
this.hello()
}
}
}
</script>
<style scoped>
</style>