gpt4 book ai didi

javascript - 如何在created()钩子(Hook)期间使用数据初始化Vue-CLI应用程序?

转载 作者:行者123 更新时间:2023-12-02 21:41:49 25 4
gpt4 key购买 nike

我正在努力更新一个大型遗留系统,因此我受到我能做什么和不能做什么的限制。

我有一个小型多组件 Vue-CLI 应用程序,它将取代多个繁重的 jQuery 表单。在某些情况下,同一页面上会有多个 Vue 应用程序实例。我需要能够将数据传递到每个实例并将该数据推出。每个实例都需要与其自己的数据集进行交互。

我目前正在我的 main.js 文件中安装应用程序,如下所示...

const mounts = document.querySelectorAll('.a-mount-spot');
for ( let i = 0; i < mounts.length; i++ ) {
let mount = mounts[i];
new Vue({
render: h => h(App)
}).$mount(mount);
}

App 是一个带有多个子组件的单文件 Vue 组件。我不知道如何让 Appcreated() Hook 期间知道它自己的 mount 。所以我想在创建组件时传入数据。 我该怎么做?

例如,所需结果的伪代码可能如下所示......

ma​​in.js

import Vue from 'vue';
import App from './App.vue';

const mounts = document.querySelectorAll('.a_mount_spot');
for ( let i = 0; i < mounts.length; i++ ) {
let mount = mounts[i];
new Vue({
init_data: { // This does not actuall pass in data
who_am_i: mount.dataset.myname
},
render: h => h(App)
}).$mount(mount);
}

App.vue

<template>
<div id="app">
{{ who_am_i }}
</div>
</template>

<script>
export default {
name: 'app',
data: function () {
return {
who_am_i: ''
}
},
created() {
this.who_am_i = '' // Some how get the init_data passed in when created
}
}
</script>

<style>
</style>

工作方法

如果我在组件生命周期中等待,直到安装它之后,我可以执行此操作...

<script>
export default {
name: 'app',
data: function () {
return {
who_am_i: ''
}
},
mounted() {
this.who_am_i = this.$el.parentElement.dataset.myname
}
}
</script>

此方法要求 HTML 如下所示...

<div class="app-wrapper" data-myname="Betty">
<div class="a-mount-spot">
</div>
<div class="app-wrapper" data-myname="Name 2">
<div class="a-mount-spot">
</div>

这感觉很怪异。在安装之前,它也不允许我访问 who_am_i。最好能提供一些有关创建的初始数据。

最佳答案

也许你可以尝试使用 Prop :

const mounts = document.querySelectorAll('.a-mount-spot');
for ( let i = 0; i < mounts.length; i++ )
{
let mount = mounts[i];
new Vue({
render: h => h(App,
{
props:
{
who_am_i: mount.parentElement.dataset.myname,
}
})
}).$mount(mount);
}

关于javascript - 如何在created()钩子(Hook)期间使用数据初始化Vue-CLI应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60348072/

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