1、Vuejs 3 筆記(只是本人筆記,大家請自行到官網看文件)
阿新 • • 發佈:2022-04-09
需要引入:
<script src="https://unpkg.com/vue@next"></script>
第一個 Vuejs 3
<div id="counter"> Counter: {{counter}} </div> const Counter = { data() { return { counter: 0 } }, mounted(){ setInterval(()=>{ this.counter++ },1000) } } Vue.createApp(Counter).mount('#counter')
v-bind指令設定 attribute
指令 都是以字首 v- 開頭
<div id="bind-attribute"> <!-- 將這個元素節點的 title attribute 和當前活躍例項的 message property 保持一致 --> <span v-bind:title="message"> 滑鼠懸停幾秒鐘檢視此處動態繫結的提示資訊! </span> </div> const AttributeBinding={ data(){ return { message: 'you loaded this page on ' + new Date().toLocaleString() } } } Vue.createApp(AttributeBinding).mount('#bind-attribute')
事件 v-on
<div id="event-handling"> <p>{{message}}</p> <button v-on:click="reverseMessage">點選翻轉 Message</button> </div> const EventHandling= { data(){ return { message: "Hello Vue.js" } }, methods:{ reverseMessage(){ this.message = this.message.split('').reverse().join('') } } } Vue.createApp(EventHandling).mount("#event-handling")
v-model 表單輸入和應用狀態之間的雙向繫結
<div id="two-way-binding"> <p>{{message}}</p> <input v-model="message"> </div> const TwoWayBinding = { data(){ return { message : 'Hello Vue!' } } } Vue.createApp(TwoWayBinding).mount('#two-way-binding')
v-if
<div id="conditional-rendering"> <span v-if="seen">現在你看到我了</span> </div> const CoditionalRendering = { data(){ return { seen: true } } } Vue.createApp(CoditionalRendering).mount("#conditional-rendering")
v-for
<div id="list-rendering"> <ol> <li v-for="todo in todos"> {{todo.text}} </li> </ol> </div> const ListRendering = { data(){ return { todos: [ {text: '111'}, {text: '222'}, {text: '333'} ] } } } Vue.createApp(ListRendering).mount('#list-rendering')
元件化開發
就是在一個頁面中,將每個部分都模組化,每個部分裡面又可以繼續模組化,形成如下圖:
Vue 的元件,就是一個預定義選項的例項,註冊元件也很簡單,如下
<div id="todo-list-app"> <ol> <!-- 建立一個 todo-item 元件例項 --> <!-- 現在我們為每個 todo-item 提供 todo 物件 todo 物件是變數,即其內容可以是動態的。 我們也需要為每個元件提供一個“key”,稍後再 作詳細解釋。 --> <todo-item v-for="item in groceryList" v-bind:todo="item" v-bind:key="item.id"></todo-item> </ol> </div> // TodoItem 就是一個預定義選項的例項,即:定義了這元件的選項 const TodoItem = { props: ['todo'], // 父元件的資料傳遞到子元件中 template: `<li>{{todo.text}}</li>` } const TodoList = { data() { return { groceryList: [ { id: 0, text: 'Vegetables' }, { id: 1, text: 'Cheese' }, { id: 2, text: 'Whatever else humans are supposed to eat' } ] } }, components: { TodoItem // 註冊一個新元件 } //... // 元件的其它 property } const app = Vue.createApp(TodoList) // 掛載 Vue 應用 app.mount('#todo-list-app')
上圖的橙色箭頭中為:子單元通過 prop 介面與父單元進行了良好的解耦。我們現在可以進一步改進 <todo-item> 元件,提供一個更為複雜的模板和邏輯,而不會影響到父應用。
在一個大型應用中,有必要將整個應用程式劃分為多個元件,以使開發更易管理。類似:
<div id="app"> <app-nav></app-nav> <app-view> <app-sidebar></app-sidebar> <app-content></app-content> </app-view> </div>