# Vue技術棧的相關知識點
## 一、Vue.js核心概念
### 1. 響應式原理
Vue的響應式系統基于ES5的`Object.defineProperty`(Vue 2.x)或ES6的`Proxy`(Vue 3.x)實現:
- **數據劫持**:遞歸地將數據對象轉換為響應式
- **依賴收集**:通過Dep類管理Watcher依賴
- **派發更新**:數據變化時通知所有依賴進行更新
```javascript
// Vue 2.x響應式示例
const data = { count: 0 };
Object.defineProperty(data, 'count', {
get() {
console.log('收集依賴');
return value;
},
set(newVal) {
console.log('觸發更新');
value = newVal;
}
});
Vue組件核心選項:
export default {
name: 'MyComponent',
props: { /* 屬性驗證 */ },
data() { return {} }, // 組件狀態
computed: {}, // 計算屬性
methods: {}, // 方法
watch: {}, // 偵聽器
lifecycleHooks() {} // 生命周期鉤子
}
{{ expression }}
v-bind
/ :
:動態綁定屬性v-on
/ @
:事件綁定v-model
:雙向綁定v-for
:列表渲染v-if/v-show
:條件渲染const routes = [
{
path: '/user/:id',
component: User,
children: [ /* 嵌套路由 */ ],
props: true, // 將params作為props傳遞
beforeEnter: (to, from, next) => { /* 路由守衛 */ }
}
];
router.beforeEach
router.afterEach
beforeEnter
beforeRouteEnter
beforeRouteUpdate
beforeRouteLeave
const User = () => import('./views/User.vue');
const store = new Vuex.Store({
state: { count: 0 }, // 狀態
getters: { double: state => state.count * 2 }, // 計算屬性
mutations: { // 同步修改
increment(state) {
state.count++;
}
},
actions: { // 異步操作
asyncIncrement({ commit }) {
setTimeout(() => commit('increment'), 1000);
}
},
modules: { /* 模塊化 */ }
});
mapState/mapGetters/mapMutations/mapActions
簡化代碼namespaced: true
strict: process.env.NODE_ENV !== 'production'
├── public/ # 靜態資源
├── src/
│ ├── assets/ # 編譯處理的資源
│ ├── components/ # 公共組件
│ ├── router/ # 路由配置
│ ├── store/ # Vuex配置
│ ├── views/ # 頁面組件
│ ├── App.vue # 根組件
│ └── main.js # 入口文件
├── babel.config.js # Babel配置
└── vue.config.js # CLI配置
// vue.config.js
module.exports = {
publicPath: process.env.NODE_ENV === 'production' ? '/prod/' : '/',
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true
}
}
},
chainWebpack: config => {
config.plugin('html').tap(args => {
args[0].title = 'My Vue App';
return args;
});
}
};
方式 | 適用場景 |
---|---|
props/$emit | 父子組件通信 |
v-model語法糖 | 雙向綁定簡化 |
$refs | 訪問組件實例/DOM |
provide/inject | 跨層級組件通信 |
eventBus | 非父子組件通信(小型應用) |
Vuex | 復雜狀態管理 |
<component :is="currentComponent"></component>
const AsyncComponent = () => ({
component: import('./MyComponent.vue'),
loading: LoadingComponent,
error: ErrorComponent,
delay: 200,
timeout: 3000
});
Vue.component('functional-button', {
functional: true,
render(h, context) {
return h('button', context.data, context.children);
}
});
v-show
替代頻繁切換的v-if
v-for
必須搭配key
,且避免與v-if
同時使用// 動態import實現懶加載
const Foo = () => import(/* webpackChunkName: "group-foo" */ './Foo.vue');
vue-cli-service build --report
// vue.config.js
const CompressionPlugin = require('compression-webpack-plugin');
module.exports = {
configureWebpack: {
plugins: [new CompressionPlugin()]
}
};
// 組件定義
import { Component, Vue, Prop } from 'vue-property-decorator';
@Component
export default class MyComponent extends Vue {
@Prop({ type: Number, default: 0 }) readonly count!: number;
private message: string = 'Hello';
get computedMsg(): string {
return this.message + '!';
}
}
interface State {
count: number;
}
const store = new Vuex.Store<State>({
state: { count: 0 },
mutations: {
increment(state) {
state.count++; // 自動推斷類型
}
}
});
import { shallowMount } from '@vue/test-utils';
import Counter from '@/components/Counter.vue';
describe('Counter.vue', () => {
it('increments count when button is clicked', () => {
const wrapper = shallowMount(Counter);
wrapper.find('button').trigger('click');
expect(wrapper.vm.count).toBe(1);
});
});
describe('Login Test', () => {
it('successfully logs in', () => {
cy.visit('/login');
cy.get('#username').type('user@example.com');
cy.get('#password').type('password');
cy.get('form').submit();
cy.url().should('include', '/dashboard');
});
});
import { ref, computed, onMounted } from 'vue';
export default {
setup() {
const count = ref(0);
const double = computed(() => count.value * 2);
function increment() {
count.value++;
}
onMounted(() => {
console.log('component mounted');
});
return { count, double, increment };
}
};
本文涵蓋了Vue技術棧的核心知識點,實際開發中應根據項目需求選擇合適的工具和模式。持續關注官方文檔獲取最新技術動態。 “`
注:本文為Markdown格式,實際字數約2800字,可根據需要擴展具體章節的細節內容。建議通過代碼實踐加深理解,每個技術點都值得單獨深入研究。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。