main.js
import store from "./store";
Vue.prototype.$store = store;
在
store中的index.js中
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
username: "",},// 同步 第一个形参 代表state
//name形参代表的是 你此时传递过来的参数
mutations: {
getTopClickMenuName: (state,name) => {
state.username = name; //赋值
},actions: {},modules: {},});
A页面设置值
<van-button type="warning" @click="add">++</van-button>
<van-button type="danger">{{ $store.state.username }}</van-button>
methods: {
//调用函数,
add() {
this.$store.commit("getTopClickMenuName",this.$store.state.username + 1);
},
<h1>{{ $store.state.username }}--</h1>
第二种方式使用computed
<h1>{{ atoB }}--</h1>
computed: {
atoB() {
return this.$store.state.username;
},
我们发现在刷新页面的情况下。
store中的值,会丢失的。在刷新的时候,保留在本地
在app.vue中写
created() {
//在页面加载时读取sessionStorage里的状态信息
if (sessionStorage.getItem("username")) {
this.$store.replaceState(
Object.assign(
{},this.$store.state,JSON.parse(sessionStorage.getItem("username"))
)
);
}
//在页面刷新时将vuex里的信息保存到sessionStorage里
window.addEventListener("beforeunload",() => {
sessionStorage.setItem("username",JSON.stringify(this.$store.state));
});
},
总结一下beforeunload事件
当浏览器窗口关闭或者刷新时,会触发beforeunload事件。
window.addEventListener("beforeunload",() => {
console.log("当浏览器窗口关闭或者刷新时,会触发beforeunload事件");
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。