【发布时间】:2018-06-29 02:35:43
【问题描述】:
我正在使用electron-vue 样板,我想在每个带有 VueX 的 Vue JS 组件中使用 Electron Webview API。
问题在于 Webview 只能在初始化后访问,因此 getTitle() 等方法未定义。
现在我的商店是这样的。
const state = {
webview: null,
homePageUrl: 'https://duckduckgo.com/?kac=0&kl=fr-fr&kp=1&kz=-1&kac=-1&k1=-1',
canGoBack: false,
canGoForward: false,
loadInProgress: false
}
const mutations = {
S_SET_WEBVIEW (state, webview) {
state.webview = webview
},
S_LOAD_URL (state, url) {
if(state.webview != null) {
state.webview.loadURL(url)
}
},
S_CAN_GO_BACK (state) {
if(state.webview != null) {
state.canGoBack = state.webview.canGoBack()
}
},
S_CAN_GO_FORWARD (state) {
if(state.webview != null) {
state.canGoForward = state.webview.canGoForward()
}
},
S_GO_BACK (state) {
if(state.webview != null && state.canGoBack != false) {
state.webview.goBack()
}
},
S_GO_FORWARD (state) {
if(state.webview != null && state.canGoForward != false) {
state.webview.goForward()
}
},
S_LOADING (state, bool) {
state.loadInProgress = bool
}
}
const actions = {
}
export default {
state,
mutations,
actions
}
这就是我在商店中初始化变量 webview(默认为 null)的方式。
mounted() {
let webview = document.getElementById('search-webview')
this.$store.commit('S_SET_WEBVIEW', webview)
// Can go back or forward (or disable btn)
this.webview.addEventListener('did-navigate', () => {
this.$store.commit('S_CAN_GO_BACK')
this.$store.commit('S_CAN_GO_FORWARD')
})
// Enable loader (spinner)
this.webview.addEventListener('did-start-loading', () => {
this.$store.commit('S_LOADING',true)
})
// Disable loader (spinner)
this.webview.addEventListener('did-stop-loading', () => {
this.$store.commit('S_LOADING',false)
})
}
在我的其他组件中,我想获取当前页面的标题,返回等等......但它总是返回该方法未定义。
this.$store.state.webBrowser.webview.getTitle()
【问题讨论】:
-
有可能你的 webview 元素还没有加载到mounted() 钩子中,你有没有试过在加载完所有内容后使用一种方法将数据传递到商店?
-
我找不到挂载后的挂钩。 Vue JS Lifecycle Diagram
-
beforeUpdate() 在 dom 重新渲染时被调用,尽管这可能不是最好的情况。
-
报错略有不同:
Error: Cannot call getTitle because the webContents is unavailable. The WebView must be attached to the DOM and the dom-ready event emitted before this method can be called. -
那么在这种情况下,您的 webview 在 Vuex 中被引用时并没有附加 dom,所以我想这没有错。
标签: javascript webview vuejs2 electron vuex