javascript - 使用按钮创建新组件
问题描述
我在 VueJs 中工作,我创建了一些组件,称为 SiteList.vue、Site.vue 和 CreateSite.vue。这些组件组成了一个更大的组件,托管在一个名为 ListContainer.vue 的文件中。这些组件加在一起是一个网站列表,用户可以反应性地添加、更改标题、删除网站和编辑功能。ListContainer.vue 将整个内容输出到 App.vue。在 App.vue 中,我在模板中创建了一个 html 表格,并在表格标签内调用 listcontainer 元素。我有一个按钮元素,我试图用它来继续在 tabletags 中创建 listcontainer 元素。因此,按钮不仅可以创建一个 listcontainer 元素,还可以创建多个元素。
我试图创建一个数组,其中包含模板元素的所有格式,但它不起作用并且感觉很hacky。
我阅读了关于动态组件的部分,我觉得这更接近了,但我就是不知道应该怎么做。我真的被困在我认为可能非常容易的事情上......
应用程序.vue
<template> <div id="app"> <!-- Injection goes here -->
<time-component/>
<table>
<tr>
<td><listcontainer/></td>
<td><listcontainer/></td>
<td><div><button @click="listcontainer++">MAKE NEW LIST</button></div></td>
</tr>
</table> </div> </template>
<script>
import TimeComponent from './components/Time.vue'
import listcontainer from "./components/ListContainer.vue"
export default { name: 'App', components: {
TimeComponent,
listcontainer, }, methods:{
addListContainer(){
}
} } </script>
<!-- CSS for global --> <style>
#app { font-family:serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; margin-top: 60px; background-color: #fff; } </style>
ListContainer.vue
<template>
<div class="large-container">
<sitelist @changeLabel="setSiteLabel" :siteListLabel="siteListLabel_d"/>
</div>
</template>
<script>
import sitelist from "./SiteList.vue"
export default {
name: "list-container",
data(){
return {
siteListLabel_d: "",
};
},
methods: {
setSiteLabel(siteListLabel){
this.siteListLabel_d = siteListLabel;
},
},
components: { sitelist }
};
</script>
<style scoped>
.large-container{
padding: 20px;
margin-left: 20px;
margin-top: 200px;
border: 1px solid;
max-width: 400px;
}
</style>
解决方案
目标是添加一个新的数组项,其中包含单击按钮时单个组件所需的所有数据。您不会将每个元素的模板放入数组中,而只是将数据放入其中。然后,您将遍历数组,v-for
并像这样为数组中的每个元素创建一个组件。作为数组一部分的数据通过 prop 绑定到组件。
这是一个例子:
<template>
<div id="app">
<button @click="addNewItem">Add</button>
<table>
<tr v-for="item in array" :key="item.id">
<td>
<listcontainer :item="item" />
</td>
</tr>
</table>
</div>
</template>
<script>
import Listcontainer from './components/ListContainer.vue';
export default {
name: 'App',
components: { Listcontainer },
data() {
return { array: [] };
},
methods:{
addNewItem() {
this.array.push({
id: Math.random(),
data: ...
});
}
}
</script>
然后 Listcontainer 应该有一个包含所有相关信息的道具:
<template>
<div>{{ item }}</div>
</template>
<script>
export default {
name: 'Listcontainer',
props: {
item: {
type: Object,
required: true
}
}
};
</script>
推荐阅读
- java - 跨面板的 Wicket AjaxIndicatorAppender
- r - fread 文件具有异常值并且 R 会话中止
- angular - 无法让 Amplify JS 中的 setupTOTP 工作 -'associateSoftwareToken'
- java - 使用 ElasticSearch 索引的多个值初始化 java bean
- sonarqube - 为 sonar.properties 中的某些文件排除一些 SonarQube 规则
- java - Java RestTemplate 挂起 204 状态码响应
- android - 如何使用约束布局在水平中心添加固定宽度的图像视图
- java - 将适当的 application.properties 名称插入@PropertySource 的方法是什么?
- java - JDBCTemplate 默认使用连接池吗?
- string - 如何将 to_string() 功能添加到枚举?