如何使用Vue的过滤器将元素添加到数组中
Vue可以被定义为一个用于构建用户界面的渐进式框架。它具有多种指令,可根据用户的需求来使用。基本核心库主要专注于构建视图层,并且很容易选择其他库或与其集成。
在下文中,我们将看到如何向数组中添加元素。数组基本上是元素的集合。在不同的实际场景中,可以使用这种将元素添加到数组中的方法。例如:可以用于创建购物清单,将员工添加到列表中等。
我们可以使用Vue的v-for指令实现上述功能。我们可以循环遍历当前数组,复制所有元素,然后将新元素添加到一个新数组中。
语法
以下是使用Vue循环(v-for指令)调用过滤器的语法。
$options.filters.addLast(data, other_parameters)
示例:向数组中添加元素
将下面的代码片段复制粘贴到您的Vue项目中,并运行Vue项目。您将在浏览器窗口上看到下面的输出。
- 文件名 – app.js
-
目录结构 — $ project/public — app.js
// Adding elements to the below list
const parent = new Vue({
el: '#parent',
data: {
arr1: ['Mike', 'John', 'Elena', 'Nick']
},
filters: {
addLast: function (arr, item_arr) {
// Using the spread syntax to add the
// items to the end of the array
const final_list = [...arr, ...item_arr]
return final_list
}
}
})
-
文件名称 – index.html
-
目录结构 — $ 项目/公共 – index.html
<javascript>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script></script>
</head>
<body>
<div id='parent'>
<p>
<strong>Current List : </strong>
<ol>
<li v-for='item in arr1'>
<strong>{{item}}</strong>
</li>
</ol>
<strong>Final List : </strong>
<ol>
<li v-for='item in $options.filters.addLast(arr1, ["Bill","Steve","Rachel"])'>
<strong>{{ item }}</strong>
</li>
</ol>
</p>
</div>
<script src='app.js'></script>
</body>
</javascript>
运行以下命令以获得以下输出−
C://my-project/ > npm run serve
完整程序
下面是一个完整的代码,使用了上面的两个代码片段 – app.js和index.html。现在你可以将下面的程序作为一个javascript文件轻松地运行。
<javascript>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script></script>
</head>
<body>
<div id='parent'>
<p>
<strong>Current List : </strong>
<ol>
<li v-for='item in arr1'>
<strong>{{item}}</strong>
</li>
</ol>
<strong>Final List : </strong>
<ol>
<li v-for=' item in $options.filters.addLast(arr1, ["Bill","Steve","Rachel"])'>
<strong>{{ item }}</strong>
</li>
</ol>
</p>
</div>
<script>
// Adding elements to the below list
const parent = new Vue({
el: '#parent',
data: {
arr1: ['Mike', 'John', 'Elena', 'Nick']
},
filters: {
addLast: function (arr, item_arr) {
// Using the spread syntax to add the
// items to the end of the array
const final_list = [...arr, ...item_arr]
return final_list
}
}
})
</script>
</body>
</javascript>
在这里我们演示了如何根据Vue.js中的数据和/或过滤器的变化轻松动态地将元素添加到数组中。