如果各组件都要用的变量多,很复杂的时候,可以用vuex
但是如果通用变量少,就可以用store方式
参考官方的“状态管理”
https://cn.vuejs.org/guide/scaling-up/state-management.html
在接下来的例子中,我主要用来获取屏幕的高度,为了在切换显示设备时能够有比较好的体验。
-
首先在src文件夹下新建store.js文件
image.png - 按照官方示例定义变量
//store.js
import { reactive } from 'vue'
export const store = reactive({
mainHeight: '',//主屏幕除header组件外的高度,自适应需要
})
- 在一个较底层的组件中获取屏幕高度,并赋值
//BasicLayout.vue
<template>
<div :style="{height: mainHeight + 'px'}">
<router-view :mainHeight="mainHeight"></router-view>
</div>
</template>
<script>
import { store } from '../store.js'
export default {
data(){
return{
clientHeight: '',
mainHeight: '',
}
},
created(){
this.setHeightVal();
},
watch: {
clientHeight(val){
this.mainHeight = val - 52 - 32;//52是header的高度,32是sidebar中button的高度
store.mainHeight = this.mainHeight;
},
},
methods: {
setHeightVal(){
this.clientHeight = document.documentElement.clientHeight;
this.mainHeight = this.clientHeight - 52 - 32;
store.mainHeight = this.mainHeight;
let that = this;
window.onresize = function () {
that.clientHeight = document.documentElement.clientHeight;
that.mainHeight = that.clientHeight - 52 - 32;//52是header的高度,32是sidebar中button的高度
store.mainHeight = that.mainHeight;
};
},
},
}
</script>
- 需要取值的地方用computed
//SiderMenu.vue
<template>
<div :style="{height: sidebarHeight}"></div>
</template>
<script>
import { store } from '../store.js';
computed:{
sidebarHeight(){
return store.mainHeight + 'px';
}
},
</script>
网友评论