首页 > 解决方案 > 如何在 created() 挂钩期间使用数据初始化 Vue-CLI 应用程序?

问题描述

我正在努力更新一个大型的 lecacy 系统,所以我受到我能做什么和不能做什么的限制。

我有一个小型的多组件 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 组件。我不知道如何在钩子中App意识到它是自己的。所以我想在创建组件时传入数据。我怎么做?mountcreated()

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

main.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);
}

应用程序.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>

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

标签: javascriptvue.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,
        {
          props:
          {
            who_am_i: mount.parentElement.dataset.myname,
          }
        })
    }).$mount(mount);
}

推荐阅读