VUE
官方文檔:https://cn.vuejs.org/
創建VUE項目
前提:已安裝 16.0 或更高版本的 Node.js
進入要創建的目錄,執行命令:npm create vue@latest
安裝依賴,啟動:
//進入項目目錄,運行命令安裝依賴
npm install
//啟動vue項目
npm run dev
VUE項目目錄結構
.vscode //編輯器生成的一些配置
node_modules // vue項目的運行依賴文件
public //資源文件
src //源碼文件,主要操作的文件夾
.gitignore //git忽略文件的配置
index.html // 項目的入口文件
package.json //npm管理文件,一些依賴的版本等
README.md // 項目介紹文件,自定義
vite.config.js // vue的配置文件
事件修飾符
在處理事件時調用 event.preventDefault() 或 event.stopPropagation() 是很常見的。盡管我們可以直接在方法內調用,但如果方法能更專注于數據邏輯而不用去處理 DOM 事件的細節會更好。
為解決這一問題,Vue 為 v-on 提供了事件修飾符。修飾符是用 . 表示的指令后綴,包含以下這些:
. stop
. prevent
. self
. capture
. once
. passive
<!-- 單擊事件將停止傳遞 -->
<a @click.stop="doThis"></a><!-- 提交事件將不再重新加載頁面 -->
<form @submit.prevent="onSubmit"></form><!-- 修飾語可以使用鏈式書寫 -->
<a @click.stop.prevent="doThat"></a><!-- 也可以只有修飾符 -->
<form @submit.prevent></form><!-- 僅當 event.target 是元素本身時才會觸發事件處理器 -->
<!-- 例如:事件處理器不來自子元素 -->
<div @click.self="doThat">...</div>
組件
一般會將組件定義在一個單獨的.vue
文件中,這被叫做單文件組件。
<script>
export default{data(){return{count:0}}
}
</script>
<template><button @click="count++">這是一個組件</button>
</template>
使用組件
一個組件可以被多次使用(同一父組件內),每使用一個組件,就創建一個新的實例。
- 在父組件中導入子組件
- 注冊組件,將導入的組件暴露給模版
- 使用組件
<script>
//1. 導入組件
import ButtonCounter from './ButtonCounter.vue'export default{//2. 注冊組件components:{ButtonCounter}
}
</script><template><h1>Child component</h1><!-- 3.使用組件 --><ButtonCounter /><ButtonCounter />
</template>
父組件向子組件傳值
- 子組件聲明
props
- 父組件傳數據給子組件
//1. 子組件聲明props
<script>export default{props:['name']}
</script><!-- 使用參數 -->
<template><h1>{{ name }}</h1>
</template>//2. 父組件傳值
<ButtonCounter name="My name is VUE" />
監聽事件
- 子組件可以用過調用內置的
$emit
方法,通過傳入事件名稱來拋出一個事件 - 父組件可以通過
v-on
或@
來選擇性地監聽組件上拋出的事件
//1. 子組件拋出hello事件
<template><button @click="$emit('hello')">點擊我拋出事件</button>
</template>//2. 父組件監聽器拋出的hello事件
<child-component @hello="alert(1)" />
插槽
父組件向子組件中傳入內容
- 子組件中定義
<slot>
作為一個占位符 - 父組件使用子組件時傳入內容
//1. 子組件中定義<slot>占位
<template><h1>插槽</h1><slot />
</template>//2. 父組件中使用子組件時,傳入內容
<child-component>This is content.
</child-component>
動態組件
有些場景會需要在兩個組件間來回切換,比如Tab,可以通過<component>
元素和特殊的is
attribute實現:
// child-component可以是 1.被注冊的組件名,也可以是 2.導入的組件對象
<component :is="child-component"></component>
當使用<component>
來在多個組件間切換時,被切換掉的組件會被卸載,可以通過<keepAlive>
組件強制被切換掉的組件扔保持存活狀態。