javascript - 如何在 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
意识到它是自己的。所以我想在创建组件时传入数据。我怎么做?mount
created()
例如,所需结果的伪代码可能如下所示......
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
。提供一些有关创建的初始数据会很好。
解决方案
也许您可以尝试使用道具:
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);
}
推荐阅读
- c++ - c++编译后报错
- javascript - Jquery删除不匹配文本的父容器
- c# - ReSharper - 转到类型结果组装顺序
- c# - 当锁定部分中设置的 volatile 变量的新值可供其他线程使用时?
- unity3d - 滚动背景重叠
- html - 输入字段只读而不使输入插件按钮只读
- python - 寻找 K 的最优值
- java - 如何在 Dropwizard 中使用 Quartz 调度程序进行 REST 调用?
- java - 用下一个替换元音不起作用
- docker - Docker Compose: Django, uWSGI, NGINX without Proxy (不同的容器)