screen_rotation
Copied to Clipboard
<html> <head> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <h3>Vue Js add item to array if does not exist using indexof method</h3> <div id="app"> <ul> <li v-for="item in myArray" :key="item">{{ item }}</li> </ul> <input type="text" v-model="newItem" placeholder="Add a new item..."> <button @click="addItem">Add Item</button> <pre v-if="error" style="color:red">{{error}}</pre> </div> <script type="module"> const app = new Vue({ el: "#app", data() { return { myArray: ['Red', 'blue', 'black'], newItem: '', error: '' }; }, methods: { addItem() { const item = this.newItem.trim(); if (item && this.myArray.indexOf(item) === -1) { this.myArray.push(item); this.newItem = ''; this.error = '' } else{ this.error = 'item alrady exist' } } } }); </script> </body> </html>