21.VUE學習之-操作data裡的陣列變異方法push&unshit&pop&shift的例項應用講解
阿新 • • 發佈:2019-01-08
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <!--<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>--> <script type="text/javascript" src="../js/vue.js"></script> </head> <body> <div id="hdcms"> <li v-for="v in comments"> {{v.content}} </li> <textarea v-model="current_content" cols="30" rows="10"></textarea><br> <button v-on:click="push('end')">發表到後面</button> <button v-on:click="push('pre')">發表到前面</button> <br> <button v-on:click="del('last')">刪除最後一條評論</button> <button v-on:click="del('first')">刪除第一條評論</button> </div> <script> var app = new Vue({ el: '#hdcms', data: { //當前使用者輸入內容 current_content: '', comments: [ {content: '後盾人'}, {content: '向軍老師'}, ] }, methods: { push(type){ var content = {content: this.current_content} switch (type) { case 'end': this.comments.push(content); break; case 'pre': this.comments.unshift(content); break; } this.current_content = ''; }, del(type){ switch (type) { case 'last': this.comments.pop(); break; case 'first': this.comments.shift(); break; } } } }); </script> </body> </html>
效果: