[英]Dynamically create boxes using vue.js
I wanted to create square boxes dynamically, based on number of array entries using vue.js.我想根据使用 vue.js 的数组条目数动态创建方形框。
eg: An array with例如:一个数组
['101','102','103'] ['101','102','103']
are passed from browser console to vue.js
script, then three square boxes with text 101
on the first box and so on should be created.从浏览器控制台传递到vue.js
脚本,然后应该创建三个方框,第一个方框上的文本为101
,依此类推。
To get you started and probably the better and easier method check out this fiddle by @bert posted in comment为了让您开始,可能是更好更简单的方法,请查看@bert在评论中发布的这个小提琴
you can also make use of Render functions so that you get powers of javascript to programmatically build your html您还可以使用Render 函数,以便获得 javascript 的功能以编程方式构建您的 html
script脚本
Vue.component("my-boxes", {
props: ["boxes"],
render(createElement){
return createElement("div",
this.boxes.map((box) => {
return createElement('div', {
style: {width: "50px", height: "50px", border: "1px solid red", margin: "5px"}
}, box);
})
)
}
})
new Vue({
el: "#app",
data(){
return{
myArr: ["101", "102", "103"]
}
}
})
template模板
<div id="app">
<my-boxes :boxes="myArr"></my-boxes>
</div>
Here is the working fiddle这是工作小提琴
Summary:概括:
render
function receives createElement
as its argument. render
函数接收createElement
作为其参数。createElement
is used to create virtual nodes which vue puts together form a virtual dOM.这个createElement
用于创建 vue 组合在一起形成虚拟 dom 的虚拟节点。 This virtual DOM is then used to create the actual HTML DOM which gets rendered o the page.然后使用这个虚拟 DOM 来创建在页面上呈现的实际 HTML DOM。boxes
to my-boxes
component which contains the array of boxes to render我们将一个 prop boxes
传递给my-boxes
组件,该组件包含要渲染的盒子数组boxes
prop to create child virtual nodes of div elements shaped like a red box containing the text我们通过这个boxes
属性映射来创建 div 元素的子虚拟节点,形状像一个包含文本的红色框
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.