vuejs,從零開始(基本使用可以了)
阿新 • • 發佈:2018-12-15
參考簡書:https://www.jianshu.com/p/94ac8b8b8f6b 說明:工作需要,下面的基本使用,一般用於工作可以了 --------------------------------------------------------------------------------------------------- <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="http://cdn.jsdelivr.net/vue/1.0.16/vue.js"></script> <title>vue.js完整例項</title> </head> <body> <!--html--> <div id="app"> 輸入您的姓名: <input type="text" v-model="name"> <p>{{ $data | json }}</p> <p>{{ name }}</p> <button v-on:click="say">歡迎點選</button> <button @click="say">歡迎點選</button> <!--loginStatus為true時會顯示的section--> <section v-if="loginStatus"> 輸入您的姓名: <input type="text" v-model="name"> <button v-on:click="say">歡迎點選</button> <button @click="switchLoginStatus">退出登入</button> </section> <!--loginStatus為false時會顯示的section--> <section v-if="!loginStatus"> 登入使用者: <input type="text"> 登入密碼: <input type="password"> <button @click="switchLoginStatus">登入</button> </section> <!--v-for 不帶索引--> <ul> <li v-for="el in products"> {{ el.name }} - ¥ {{ el. price }} - {{ el. category }} </li> </ul> <!--v-for 帶索引--> <ul> <li v-for="el in products"> {{ $index }} - {{ el.name }} - ¥ {{ el. price }} - {{ el. category }} </li> </ul> <!--v-for 帶索引--> <ul> <li v-for="(index,el) in products"> {{ index }} - {{ el.name }} - ¥ {{ el. price }} - {{ el. category }} </li> </ul> <!--計算屬性Computed--> 輸入一個數字: <input type="text" v-model="value"> <p>計算結果:{{ square }}</p> 輸入1~10內的數字: <input type="text" v-model="value"> <p>計算結果:{{ resultMsg }}</p> </div> </body> <!--js--> <script> // 建立一個新的Vue例項,並設定掛載點 var V = new Vue({ el: '#app', data: { // v-model,雙向資料繫結 name: '_Appian', products: [ {name: 'microphone', price: 25, category: 'electronics'}, {name: 'laptop case', price: 15, category: 'accessories'}, {name: 'screen cleaner', price: 17, category: 'accessories'}, {name: 'laptop charger', price: 70, category: 'electronics'}, {name: 'mouse', price: 40, category: 'electronics'}, {name: 'earphones', price: 20, category: 'electronics'}, {name: 'monitor', price: 120, category: 'electronics'} ], value: null, randNum: 5//第一次隨機數為5 }, computed: { // 計算屬性Computed square: function () { return this.value * this.value; }, resultMsg: function () { if (this.value == this.randNum) { this.randNum = this.getRandNum(1, 10); return '你猜對了!'; } else { this.randNum = this.getRandNum(1, 10); return '猜錯了,再來!'; } }, }, methods: { // v-on / @click 事件繫結 say: function () { alert('歡迎' + this.name); }, switchLoginStatus: function () { // 利用v-if或者v-show進行條件判定 this.loginStatus = !this.loginStatus; }, getRandNum: function (min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } } }); </script> </html>