我們創建一個項目,這個項目我們細說Vue。
一.如何在項目中添加模塊
我們通過npm 進行 安裝 模塊。
首先我們通過cmd.exe cd進入你的項目根目錄,必須存在package.json文件,安裝完之后就自動引入了。
如何在項目中添加模塊呢?我們找到main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
//在這里可以引用第三方模塊
import 'bootstrap/dist/css/bootstrap.css' Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', components: { App }, template: '<App/>' })
二.程序員典型開場白“Hello,World”
vue頁面中的樣式都有互用性,那么如何讓一個webpack的樣式具有單一性呢.可以在style標簽中添加scoped
...b話少說,讓我們看下helloWorld吧。
<template> <div id="app" class="container"> <h1>{{text}}</h1> </div> </template> <script> export default{ name :'app', data(){ return{ text:"hello,Vue" } } } </script>
data就猶如C#中的參數一樣,它是為View做准備的,就猶如MVC一樣,這種數據驅動和組件化就叫做MVVM模式
三.綁定復雜數據(集合)
數據是這樣的:
data(){
return{ text:"hello,Vue", stus:[ {sid:11,name:'小明11',age:21}, {sid:12,name:'小明12',age:22}, {sid:13,name:'小明13',age:23}, {sid:14,name:'小明14',age:24}, {sid:15,name:'小明15',age:25}, {sid:16,name:'小明16',age:26}, {sid:16,name:'小明16',age:26}, ] } }
我們可以通過vue的v-for去遍歷它。
<div v-for="stu in stus" :key="stu"> <h4>{{stu.name}}</h4> </div>
但我們值得思考的是,如何獲取下標呢,我們說的並不是sid ---序號,我們可以這么搞定
<div v-for="(stu,index) in stus" :key="stu"> <h4>{{index}} {{stu.name}}</h4> </div>
這第二個參數還有一個關鍵字就是attr我們可以這么做
<tr v-for="(p,attr) in person" :key="p">
<td>{{attr}}</td>
<td>{{p}}</td>
</tr>
person:{
name:'張三', gender:'男', age:30, height:170, weight:200, }
這樣我們就可以知道它的屬性名了。
有可能你覺得綁定集合我們已經說完了,聰明的同學應該發現,這樣的數據格式非常的整潔,那如果他們的列數不同我們應該怎么辦呢?我們可以這么做!
<div v-for="(stu,index) in stus" :key="stu"> <h4>這是第{{index}}個學生</h4> <table class="table table-bordered table-hover"> <tr v-for="(p,attr) in stu" :key="p"> <td>{{attr}} {{stu.name}}</td> </tr> </table> </div>
四.vue的view-model
<input type="text" class="form-control" v-model="user.name"> <h4>{{user.name}}</h4>
user:
{
name:'', pwd:'' }
五.@Click事件驅動
和winfrom事件驅動類似,vue中事件寫在methods中,我們簡單的做一下登錄功能
事件驅動的標識通過@Click觸發
methods:{
MyLogin(){
if(this.user.name==="admin"&&this.user.pwd==="123456"){ alert("登錄成功"); } } }
值得一提的是,如果方法需要參數,但是通過事件調用的時候沒有給傳遞參數,那么參數的值等於此方法的Dom元素所觸發的事件對象。例如button 就等於MouseEvent,在ES6新標准中,方法可以自行定制默認值,如果不傳值就是默認值的了!
傳入值
如果不傳入
六.v-if方法
<h3 v-if="age<16">少年</h3> <h3 v-else-if="age<30">青年</h3> <h3 v-else-if="50">中年</h3> <h3 v-else>老年</h3>
七.v-show
<h3 v-show="age<30">小於30歲</h3> <h3 v-show="age>30">大於30歲</h3>
這和if沒有什么區別 而且和else的機制不同,show方法只是控制一下style:display:none||block 。。。
結語:希望大家學的開心,有什么問題在下方留言,覺得有用的話點個推薦吧!