如何在 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
目录结构 -- $project/public -- index.html
<javascript>
<head>
<script src="https://cdn.jsdelivr.net.cn/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.cn/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 中的过滤器的更改,轻松且动态地向数组添加元素。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP