5

vue3创建全局属性和方法

 2 years ago
source link: https://segmentfault.com/a/1190000040224048
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

vue3创建全局属性和方法

vue3中取消了过滤器filter,如果组件中单独使用可以用computed、watch来替换。但是想全局创建一个之前的vue2中的filter,我们就要使用在vue全局中挂在属性或者方法。

1、打开main.js文件,写入自己的全局属性或者方法。

import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/lib/theme-chalk/index.css'
import './assets/scss/global.scss'
import App from '@/App.vue'
import router from '@/router'
import store from '@/store'
// 开始
const app = createApp(App)
// 创建方法
const dateTimeSub = (value) => {
  if (value) {
    return value.split(' ')[0]
  }
}
// 挂在全局方法
app.config.globalProperties.$filters = dateTimeSub
// 主意这里改为app.use
app.use(store).use(router).use(ElementPlus).mount('#app')

2、使用

// 引入getCurrentInstance
import { reactive, ref, getCurrentInstance } from 'vue'
setup (props, {emit}) {
    // 获取全局属性和方法
    const { ctx, proxy } = getCurrentInstance()
    // ctx和proxy都可以访问到定义的全局方法,但是ctx只能在本地使用,线上环境使用proxy
    ...
    
    return {
      proxy
    }

image.png

<template>
  <div>{{proxy.$filters('2020-06-22 10:55')}}<div>
</template>

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK