gpt4 book ai didi

javascript - Laravel 和 VueJS,访问 Vue 实例。

转载 作者:行者123 更新时间:2023-12-01 01:40:19 27 4
gpt4 key购买 nike

我想更改数据属性并在 Laravel 中的 Vue 实例上运行一个方法。然而,由于使用 webpack 和 laravel,我似乎无法按照我期望的方式访问实例:

所以 window.app 似乎不是我的 Vue 类的正确实例。

下面是我正在加载的 Blade View ,如您所见,我将一个脚本标记附加到我的主 layout.blade.php 中,只是尝试更改 Vue 实例数据属性,然后运行一个方法。

@push('scripts')
<script>
app.unsaved = true;
app.triggerEvent(null, 'models', null);
</script>
@endpush

下面是我的 app.js (resources/assets/js/app.js) 的一部分:

const app = new Vue({
el: '#app',
components: {
'models-select': ModelsSelect
},
data: {
showModel: false,
unsaved: false
},
mounted: function() {

let _self = this;

(function() {

document.querySelectorAll("input, textarea, select").forEach(function(e) {
e.addEventListener('change', function() {
_self.unsaved = true;
e.classList.add('is-changed');
});
});

function unloadPage(){
if (_self.unsaved) return 'You appear to have un-saved changes!';
}

window.onbeforeunload = unloadPage;

})();

},
methods: {

triggerEvent: function(event, target, property)
{
app.$refs[target].update(event, property);
}

如您所见,我希望通过我在 app.js 中定义的全局 app 变量来操作 Vue 实例。然而,情况似乎并非如此。

运行 triggerEvent 方法时出现以下错误:

app.triggerEvent is not a function

最佳答案

在您的 app.js 中文件,更改const app = new Vue({window.app = new Vue({ .

然后在你的 <script> 内标签,将其更改为这个。

<script>
window.app.unsaved = true;
window.app.triggerEvent(null, 'models', null);
</script>

关于javascript - Laravel 和 VueJS,访问 Vue 实例。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52479527/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com