var app = new Vue({
el: '#app',
data: {
sharedData : ""
},
methods: {
goToPageB: function() {
if (some condition is met) {
window.location.href="pageB.html";
sharedData = 1234; <------- I want to access sharedData in page B as well
}
}
}
Run Code Online (Sandbox Code Playgroud)
我是 Vue 的新手,我做了一个虚拟登录页面,并尝试让我的主页根据用户名显示 sharedData。但是在我的应用程序定向到页面 B 后数据总是丢失。我该如何解决这个问题?
您可以将其sharedData作为 URL 参数传递:'window.location.href="pageB.html?sharedData=myData"' 并在其他页面中访问它。如果你一直在使用vue-router,你可以这样做
this.$route.params.sharedData
Run Code Online (Sandbox Code Playgroud)
由于您没有使用它,您可以只使用普通的 javascript 来获取它,但是您必须编写一个如下所示的辅助函数来获取参数,如解释here
var QueryString = function () {
// This function is anonymous, is executed immediately and
// the return value is assigned to QueryString!
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
// If first entry with this name
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = decodeURIComponent(pair[1]);
// If second entry with this name
} else if (typeof query_string[pair[0]] === "string") {
var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ];
query_string[pair[0]] = arr;
// If third or later entry with this name
} else {
query_string[pair[0]].push(decodeURIComponent(pair[1]));
}
}
return query_string;
}();
Run Code Online (Sandbox Code Playgroud)
您可以使用集中状态管理来管理您的共享数据,除非您重新加载页面,否则这些数据将跨页面可用。
您可以定义您的状态,如下所示:
var store = {
state: {
message: 'Hello!'
},
setMessageAction (newValue) {
this.state.message = newValue
},
clearMessageAction () {
this.state.message = 'action B triggered'
}
}
Run Code Online (Sandbox Code Playgroud)
您可以在您的组件中使用它,如下所示:
var vmA = new Vue({
data: {
privateState: {},
sharedState: store.state
}
})
var vmB = new Vue({
data: {
privateState: {},
sharedState: store.state
}
})
Run Code Online (Sandbox Code Playgroud)
然而 Vue 生态系统也有一个专用的redux类似状态管理系统,称为vuex,它在社区中非常流行。您将所有项目/用户等存储在 vuex状态中,并且每个组件都可以从中央状态读取/更新。如果它被一个组件更改,则更新版本可用于所有组件。您可以使用vuex 本身中的操作在一个地方启动数据。
下面是架构图:
您可以在此处查看我对类似问题的回答,并查看有关如何调用 api 并在商店中保存数据的示例。
小智 5
看起来您并不真的需要为这么小的事情使用状态管理。如果您只是想将数据从一个子组件传递到另一个子组件,那么我建议使用事件总线。
有时,两个组件可能需要相互通信,但它们不是彼此的父/子组件。在简单的场景中,您可以使用一个空的 Vue 实例作为中央事件总线:
var bus = new Vue()
// in component A's method
bus.$emit('id-selected', 1)
// in component B's created hook
bus.$on('id-selected', function (id) {
// ...
})
Run Code Online (Sandbox Code Playgroud)
在更复杂的情况下,您应该考虑采用专用的状态管理模式。
| 归档时间: |
|
| 查看次数: |
13186 次 |
| 最近记录: |