通过 getData() 方法获取到数据对象,想要在屏幕方向改变的时候,给获取到的对象设置 orientation,能实时修改
使用 reactive 包裹, template 直接使用全局变量下的属性,watch 直接监听对应属性
main.js
const config = reactive(getData())
// 设置屏幕方向
const setOrientation = () => {
config.orientation = getOrientation()
window.config.orientation = getOrientation()
}
setOrientation()
document.addEventListener('DOMContentLoaded', setOrientation)
// 绑定屏幕旋转事件
window.addEventListener('resize', setOrientation)
window.mraid.addEventListener('sizeChange', setOrientation)
// 避免锁定屏幕方向的情况下横屏进入,获取方向不对
setTimeout(setOrientation, 1000)
app.config.globalProperties.$config = config
app.provide('config', readonly(config))
*.vue 模板中直接使用
<Logo v-if="$config.orientation === 'portrait'"/>
监听config 某个属性
const config = inject('config')
// 监听屏幕方向的改变,改变后再调用初始化样式的方法
watch(() => config.orientation, init, { immediate: true })
或
const internalInstance = getCurrentInstance()
const { $config } = internalInstance.appContext.config.globalProperties
// 监听屏幕方向的改变,改变后再调用初始化样式的方法
watch(() => $config.orientation, init, { immediate: true })