1. 程式人生 > >vue的基礎用法

vue的基礎用法

CA class 聲明變量 AR sem 字符串 ML for inf

基礎用法(沒有搭建框架就在html文件裏演示)

一、 Hello World起步

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello World</title>
</head>
<body>
    <!-- 模板 -->
    <div id="app">
        <!-- 聲明式渲染 -->
        <h1>{{ msg }}</h1>
    </div>

    <!-- 引入vue -->
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script>
        // 創建一個vue對象,同時將這個對象掛載到 #app(這裏是元素id) 的元素上
        let app = new Vue({
            // 掛載點
            el: ‘#app‘,
            // Vue 對象中管理的數據 VM ( ViewModel ), 可以直接在面板上通過聲明來進行數據訪問
            data: {
                msg: ‘Hello World‘
            }
        })
    </script>
</body>
</html>

瀏覽器顯示如圖:技術分享圖片

二、模板語法

2.1、v-html指令

雙大括號會將數據解釋為純文本,而非 HTML 。為了輸出真正的 HTML ,你需要使用 v-html 指令 被插入的內容都會被當做 HTML —— 數據綁定會被忽略。註意,你不能使用 v-html 來復合局部模板,因為 Vue 不是基於字符串的模板引擎。組件更適合擔任 UI 重用與復合的基本單元

<html>
<!-- ===== 2、v-heml 指令   ===== -->
<div id="app2" v-html="rawHtml"></div>

<!-- script -->
    // 2、v-heml 指令
    let app2 = new Vue({
        el: ‘#app2‘,
        data() {
            return {
                rawHtml: ‘<h1>v-heml 指令:hello world</h1>‘
            }
        }
    })

瀏覽器顯示如圖:技術分享圖片

2.2、V-bind指令

v-bind 屬性被稱為指令。指令帶有前綴 v-,以表示它們是 Vue.js 提供的特殊屬性。這個指令的簡單含義是說: 將這個元素節點的 title 屬性和 Vue 實例的 message 屬性綁定到一起。

<html>
<!-- ===== 3、v-bind 指令   ===== -->
    <div id="app3">
        <span v-bind:title:="message">3、v-bind指令:鼠標懸停</span>
    </div>

<script>
        let app3 = new Vue({
            el: ‘#app3‘,
            data() {
                return {
                    message: ‘頁面加載於 ‘ + new Date().toLocaleString(),
                    title: ‘你好程序猿‘
                }
            }
        })

瀏覽器顯示如圖:技術分享圖片

沒找到懸停時顯示不出來的原因,後面在看看

2.3、Class 與 Style 綁定

我們也可以在對象中傳入更多屬性用來動態切換多個 class 。此外, v-bind:class 指令可以與普通的 class 屬性 共存。如下模板:

第一種: 綁定某一個 Class

<css>
    .test {
        color: red;
    }
    .test1 {
        color: blue;
    }

<html>
<!-- ===== 4、v-bind 指令 Class 與 Style 綁定  ===== -->
<div id="app4">
    <!-- 這個class是取決於isActive和hasError那個為true -->
    <span class="static" v-bind:class="{test: isActive, ‘test1‘: hasError}">4、Class 與 Style 綁定:你好程序猿</span>
</div>

<js>
// 4、v-bind 指令 Class 與 Style 綁定
let app4 = new Vue({
    el: ‘#app4‘,
    data: {
        isActive: false,
        hasError: true
    }
})

瀏覽器顯示效果如圖: 技術分享圖片

第二種: 直接綁定數據裏的一個對象

<css>
    .test {
        color: red;
    }
    .test1 {
        color: blue;
    }

<html>
<!-- ===== 4、v-bind 指令 Class 與 Style 綁定  ===== -->
<div id="app4-2">
    <span class="static" v-bind:class="classObj">4、Class 與 Style 綁定2:你好程序猿</span>
</div>

<js>
let app4A = new Vue({
    el: ‘#app4-2‘,
    data: {
        classObj: {
            test: true,
            test1: false
        }               
    }
})

瀏覽器顯示效果如圖:技術分享圖片

第三種: 數組語法

<css>
    .test {
        color: red;
    }
    .test1 {
        color: blue;
    }

<html>
<!-- ===== 4、v-bind 指令 Class 與 Style 綁定  ===== -->
<div id="app4-3">
    <span class="static" v-bind:class="[active, active2]">4、Class 與 Style 綁定3:你好程序猿</span>
</div>

<js>
let app4B = new Vue({
    el: ‘#app4-3‘,
    data: {
        active: ‘test‘,
        active2: ‘test1‘                
    }
})

瀏覽器顯示效果如圖: 技術分享圖片

綁定內嵌style就不說了可以查一下,和這個差不多!!!!

2.4、條件與循環

第一種: v-if

<html>
<div id="app5">
    <!-- 通過if else 指令來控制元素的顯示 -->
    <p v-if="ifElse">5、if: 我喜歡寫代碼</p>
    <p v-else>5、else: 我不喜歡寫代碼</p>
</div>

<js>    
let app5 = new Vue({
    el: ‘#app5‘,
    data: {
        ifElse: false               
    }
})  

還可以這樣判斷,這裏就不在做例子了
<div v-if="type === ‘A‘">  A </div> 
<div v-else-if="type === ‘B‘">  B </div>

第二種: v-for

<html>
<div id="app5-1">
    <!-- 數組 -->
    <ul>
        <li v-for="(item, index) in arr">
            5、for數組:{{index}}: {{item}}
        </li>
    </ul>
    <!-- 對象 -->
    <ul>
        <li v-for="(value, key, index) in obj">
            5、for對象: {{index}}: {{key}}={{value}}
        </li>
    </ul>
</div>

<js>

let app5A = new Vue({
    el: ‘#app5-1‘,
    data: {
        // 數組
        arr: [‘zhangsan‘, ‘lisi‘, ‘guanyu‘],
        // 對象
        obj: {
            name: ‘zhangsan‘,
            age: 21,
            gender: ‘male‘
        }           
    }
})

叠代整數
<p v-for="n in 10">{{ n }}</p>
結果: 1 2 3 4 5 6 7 8 9 10

2.5:、處理用戶輸入

<html>
<!-- 第一種: v-on 指令 -->
<div id="app6">
    <p>6、v-on:{{msg}}</p>
    <!-- v-on 指令綁定一個監聽事件用於調用我們 Vue 實例中定義的方法 -->
    <button v-on:click="reverseMsg">6、v-on:點擊</button>
</div>
<!-- 第二種: v-model 指令 -->
<!-- 在表單輸入和應用狀態中做雙向數據綁定 -->
<div id="app6-1">
    <p>6、v-model:{{msg}}</p>
    <input type="text" v-model="msg">       
</div>

<js>
// 第一種: v-on指令
// 在監聽事件中觸發對 this.data的修改
let app6 = new Vue({
    el: ‘#app6‘,
    data: {
        msg: ‘hello vue‘
    },
    methods: {
        reverseMsg: function() {
            // this.msg 是指的data中的msg屬性
            // 當this.data 中的屬性值發生變化,視圖也會重新渲染
            this.msg = this.msg.split(‘‘).reverse().join(‘‘)
        }
    }
})
// 第二種: v-model 指令
// 在表單輸入和應用狀態中做雙向數據綁定
let app6A = new Vue({
    el: ‘#app6-1‘,
    data: {
        msg: ‘hello 程序員‘
    }
})

三、組件

3.1 組件是什麽

組件可以擴展HTML元素,封裝可重用的代碼。在較高層面上,組件是自定義元素,Vue.js的編譯器為它添加特殊功能。在有些情況下,組件也可以是原生HTML元素形式,以is特性擴展。

3.2 組件的註冊或創建

<html>
<!-- 全局註冊 -->
<div id="app7">
    <hello></hello>
</div>
<!-- 局部註冊 -->
<div id="app7-1">
    <hello></hello>
</div>

<js>
// 全局註冊
Vue.component(‘hello‘, {
    template: ‘<div>7、全局註冊:Hello World</div>‘
})

let app7 = new Vue({
    el: ‘#app7‘
})

// 局部註冊: 通過使用組件實例選項註冊,可以使用組件僅在另一個實例/組件的作用域中可用
let helloVue = {
    template: ‘<div>7、局部註冊: Hello World</div>‘
}
let app7A = new Vue({
    el: ‘#app7-1‘,
    components: {
        ‘hello‘: helloVue
    }
})

=

註意:當使用DOM作為模板時(例如,將el選項掛載到一個已存在的元素上),
你會受到HTML的一些限制,因為Vue只有在瀏覽器解析和標準化HTML後才能獲取模板內容。
尤其像這些元素<ul> <ol> <table> <select>限制了能被它包裹的元素,<option>只能出現在其它元素內部。
例如: 

<html>
//這個會報錯
<table id="app7-2">
    <!-- 自定義組件 <my-row>被認為是無效的內容,因此在渲染的時候會導致錯誤 -->
    <my-row></my-row>
</table>

//這個是正確的
<table id="app7-3">
    <!-- 變通的方法,使用特殊的is屬性 -->
    <tr is="my-tr"></tr>
</table>

<js>
// 特殊
let trRow = {
    template: `
        <tr>
            <td>7、特殊: is: HTML/</td>
            <td>7、特殊: is: CSS/</td>
            <td>7、特殊: is: JS</td>
        </tr>
    `
}

let app7B = new Vue({
    el: ‘#app7-3‘,
    components: {
        ‘my-tr‘: trRow
    }
})

3.3、data

<html>
div id="app8">
    <vue-counter></vue-counter>
    <vue-counter></vue-counter>
    <vue-counter></vue-counter>
</div>

<js>
let data = {
    counter: 0
}

Vue.component(‘vue-counter‘, {
    template: ‘<button @click="counter += 1">8、data: {{counter}}</button>‘,
    // data是一個函數,因此Vue不會警告
    // 但是我們為沒有個組件返回了同一個對象引用
    data: function() {
        // return data // 由於三個組件共享了同一個data,因此增加一個counter會影響所有組件,點擊button按鈕的時候全部的按鈕上的counter變量值都會一起變
        // 改為如下代碼
        // return {
        //  counter: 0
        // }
    }
})
let app8 = new Vue({
    el: ‘#app8‘
})

3.4、 Prop的使用

組件實例的作用域是孤立的。這意味著不能並且不應該在子組件的模板內直接引用父組件的數據。可以使用props把數據傳給子組件
props是父組件用來傳遞數據的一個定義屬性。子組件需要顯示的用props選項聲明“props”

<html>
<div id="app9">
    <container></container>
</div>

<js>
// 聲明變量   對象
let container = {
    template: `
        <div>
            <span>9、props的使用: 容器組件</span>
            <child :msg="message" />
        </div>
    `,
    data() {
        return {
            message: ‘9、props的使用: 動態props‘
        }
    }
}
let child = {
    template: `
        <div>
            <span>子組件</span>
            {{ msg }}
        </div>
    `,
    // props在這裏使用
    props: [‘msg‘]
}
// 註冊組件
Vue.component(‘container‘, container);
Vue.component(‘child‘, child);

let app9 = new Vue({
    el: ‘#app9‘
})

3.5、 單向數據流

prop是單向綁定的,當父級組件的屬性變化時,將傳導給子組件,但是不會反過來。這是為了防止子組件無意修改了父組件的狀態————這回讓應用的數據流難以理解

這個例子和3.4的例子差不多,可以對比一下
<html>
div id="app10">
    <containers></containers>
</div>

<js>
// 聲明變量   對象
let containers = {
    template: `
        <div>
            <span>10、props的使用: 容器組件</span>
            <input type="text" v-model=‘message‘ name="" value="">
            <childs :msg="message" />
        </div>
    `,
    data() {
        return {
            message: ‘10、props的使用: 動態props‘
        }
    }
}
let childs = {
    template: `
        <div>
            <span>子組件</span>
            <input type="text" v-model=‘message‘ name="" value="">
            {{ message }}
        </div>
    `,
    // props在這裏使用
    props: [‘msg‘],
    data() {
        return {
            message: this.msg
        }
    }
}
// 註冊組件
Vue.component(‘containers‘, containers);
Vue.component(‘childs‘, childs);

let app10 = new Vue({
    el: ‘#app10‘
})

3.6、自定義事件

父組件是使用props傳遞數據給子組件,但如果子組件要把數據傳遞回去,應該用自定義事件方法來做

=

使用$on(eventName)監聽事件
使用$emit(eventName)觸發事件

<html>
<div id="app11">
    <containerS></containerS>
</div>
<js>
// 聲明變量   對象
let containerS = {
    // :msg 動態props
    // v-on:click 監聽子組件 $emit 觸發的事件
    template: `
        <div>
            <span>11、props的使用: 容器組件</span>
            <input type="text" v-model=‘message‘ />
            <childS :msg="message" v-on:click=‘setMessage‘ />
        </div>
    `,
    data() {
        return {
            message: ‘11、hello‘
        }
    },
    methods: {
        setMessage(msg) {
            this.message = msg
        }
    }
}
let childS = {
    template: `
        <div>
            <span>子組件</span>
            <input type="text" v-model=‘message‘ v-on:input=‘setMessage‘ />
            {{ message }}
        </div>
    `,
    // props在這裏使用
    props: [‘msg‘],
    data() {
        return {
            message: this.msg
        }
    },
    methods: {
        setMessage() {
            // 子組件觸發父級組件監聽的click事件
            this.$emit(‘click‘, this.message)
        }
    }
}
// 註冊組件
Vue.component(‘containerS‘, containerS);
Vue.component(‘childS‘, childS);

let app11 = new Vue({
    el: ‘#app11‘
})

源代碼:github

路由的基本用法可以去看一下官網的文檔

vue的基礎用法