✨ Vue2 中的 ref 引用机制详解
This commit is contained in:
parent
cdbdbec0f8
commit
85c1ae88d5
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,20 @@
|
|||
<template>
|
||||
<School />
|
||||
<Student />
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import School from "./compontens/School.vue";
|
||||
import Student from "./compontens/Student.vue";
|
||||
|
||||
export default {
|
||||
name: "App",
|
||||
data() {
|
||||
return {};
|
||||
},
|
||||
compontens: {
|
||||
School,
|
||||
Student,
|
||||
},
|
||||
};
|
||||
</script>
|
|
@ -0,0 +1,3 @@
|
|||
<template>
|
||||
<h2>学校。。。</h2>
|
||||
</template>
|
|
@ -0,0 +1,3 @@
|
|||
<template>
|
||||
<h2>学生</h2>
|
||||
</template>
|
|
@ -0,0 +1,13 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>单文件内容</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
<script type="module" src="../../js/vue@2.7.16.js"></script>
|
||||
<script type="module" src="./main.js"></script>
|
||||
</html>
|
|
@ -0,0 +1,9 @@
|
|||
import App from "./App.vue";
|
||||
|
||||
new Vue({
|
||||
el: "#app",
|
||||
template: "<App></App>",
|
||||
compontens: {
|
||||
App,
|
||||
},
|
||||
});
|
|
@ -0,0 +1,23 @@
|
|||
.DS_Store
|
||||
node_modules
|
||||
/dist
|
||||
|
||||
|
||||
# local env files
|
||||
.env.local
|
||||
.env.*.local
|
||||
|
||||
# Log files
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
|
||||
# Editor directories and files
|
||||
.idea
|
||||
.vscode
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
|
@ -0,0 +1 @@
|
|||
shamefully-hoist=true
|
|
@ -0,0 +1,24 @@
|
|||
# demo2
|
||||
|
||||
## Project setup
|
||||
```
|
||||
pnpm install
|
||||
```
|
||||
|
||||
### Compiles and hot-reloads for development
|
||||
```
|
||||
pnpm run serve
|
||||
```
|
||||
|
||||
### Compiles and minifies for production
|
||||
```
|
||||
pnpm run build
|
||||
```
|
||||
|
||||
### Lints and fixes files
|
||||
```
|
||||
pnpm run lint
|
||||
```
|
||||
|
||||
### Customize configuration
|
||||
See [Configuration Reference](https://cli.vuejs.org/config/).
|
|
@ -0,0 +1,5 @@
|
|||
module.exports = {
|
||||
presets: [
|
||||
'@vue/cli-plugin-babel/preset'
|
||||
]
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "es5",
|
||||
"module": "esnext",
|
||||
"baseUrl": "./",
|
||||
"moduleResolution": "node",
|
||||
"paths": {
|
||||
"@/*": [
|
||||
"src/*"
|
||||
]
|
||||
},
|
||||
"lib": [
|
||||
"esnext",
|
||||
"dom",
|
||||
"dom.iterable",
|
||||
"scripthost"
|
||||
]
|
||||
}
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
{
|
||||
"name": "demo2",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"serve": "vue-cli-service serve",
|
||||
"build": "vue-cli-service build",
|
||||
"lint": "vue-cli-service lint"
|
||||
},
|
||||
"dependencies": {
|
||||
"core-js": "^3.8.3",
|
||||
"vue": "^2.6.14"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.12.16",
|
||||
"@babel/eslint-parser": "^7.12.16",
|
||||
"@vue/cli-plugin-babel": "~5.0.0",
|
||||
"@vue/cli-plugin-eslint": "~5.0.0",
|
||||
"@vue/cli-service": "~5.0.0",
|
||||
"eslint": "^7.32.0",
|
||||
"eslint-plugin-vue": "^8.0.3",
|
||||
"vue-template-compiler": "^2.6.14"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"root": true,
|
||||
"env": {
|
||||
"node": true
|
||||
},
|
||||
"extends": [
|
||||
"plugin:vue/essential",
|
||||
"eslint:recommended"
|
||||
],
|
||||
"parserOptions": {
|
||||
"parser": "@babel/eslint-parser"
|
||||
},
|
||||
"rules": {}
|
||||
},
|
||||
"browserslist": [
|
||||
"> 1%",
|
||||
"last 2 versions",
|
||||
"not dead"
|
||||
],
|
||||
"packageManager": "pnpm@10.8.1+sha512.c50088ba998c67b8ca8c99df8a5e02fd2ae2e2b29aaf238feaa9e124248d3f48f9fb6db2424949ff901cffbb5e0f0cc1ad6aedb602cd29450751d11c35023677"
|
||||
}
|
File diff suppressed because it is too large
Load Diff
Binary file not shown.
After Width: | Height: | Size: 4.2 KiB |
|
@ -0,0 +1,17 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1.0">
|
||||
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
|
||||
<title><%= htmlWebpackPlugin.options.title %></title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>
|
||||
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
|
||||
</noscript>
|
||||
<div id="app"></div>
|
||||
<!-- built files will be auto injected -->
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,14 @@
|
|||
<template>
|
||||
<div id="app">
|
||||
<Demo1 />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import Demo1 from "@/views/demo1/index.vue";
|
||||
|
||||
export default {
|
||||
name: "App",
|
||||
components: { Demo1 },
|
||||
};
|
||||
</script>
|
Binary file not shown.
After Width: | Height: | Size: 6.7 KiB |
|
@ -0,0 +1,9 @@
|
|||
import Vue from 'vue'
|
||||
import App from './App.vue'
|
||||
|
||||
Vue.config.productionTip = false
|
||||
|
||||
new Vue({
|
||||
render: h => h(App),
|
||||
})
|
||||
.$mount('#app')
|
|
@ -0,0 +1,18 @@
|
|||
<template>
|
||||
<div class="demo">
|
||||
<h2>学校名称:{{ name }}</h2>
|
||||
<h2>学校地址:{{ address }}</h2>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
name: "SchoolInfo",
|
||||
data() {
|
||||
return {
|
||||
name: "Bunny",
|
||||
address: "昆山市印象花园",
|
||||
};
|
||||
},
|
||||
};
|
||||
</script>
|
|
@ -0,0 +1,30 @@
|
|||
<template>
|
||||
<div id="app">
|
||||
<h1 ref="title" v-text="message"></h1>
|
||||
<button @click="ShowDom">输出上方DOM元素</button>
|
||||
<SchoolInfo ref="schoolInfoRef" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import SchoolInfo from "@/views/demo1/components/SchoolInfo.vue";
|
||||
|
||||
export default {
|
||||
name: "App",
|
||||
components: { SchoolInfo },
|
||||
data() {
|
||||
return {
|
||||
message: "学习Vue2",
|
||||
};
|
||||
},
|
||||
|
||||
methods: {
|
||||
ShowDom() {
|
||||
// 获取当前Ref对象内容
|
||||
console.log("@@@", this.$refs.title);
|
||||
// 获取子组件对象实例
|
||||
console.log("@@@", this.$refs.schoolInfoRef);
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
|
@ -0,0 +1,168 @@
|
|||
# Vue2 中的 ref 引用机制详解
|
||||
|
||||
## 一、ref 的基本概念
|
||||
|
||||
`ref` 是 Vue2 提供的一种特殊的属性,用于直接访问 DOM 元素或子组件实例。它比传统的 `document.getElementById` 等方式更适合在 Vue 生态中使用。
|
||||
|
||||
## 二、代码解析
|
||||
|
||||
```html
|
||||
<template>
|
||||
<div id="app">
|
||||
<!-- 绑定到DOM元素 -->
|
||||
<h1 ref="title" v-text="message"></h1>
|
||||
<button @click="ShowDom">输出上方DOM元素</button>
|
||||
|
||||
<!-- 绑定到子组件 -->
|
||||
<SchoolInfo ref="schoolInfoRef" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import SchoolInfo from "@/components/SchoolInfo.vue";
|
||||
|
||||
export default {
|
||||
name: "App",
|
||||
components: { SchoolInfo },
|
||||
data() {
|
||||
return { message: "学习Vue2" };
|
||||
},
|
||||
methods: {
|
||||
ShowDom() {
|
||||
// 访问DOM元素
|
||||
console.log(this.$refs.title); // 输出: <h1>学习Vue2</h1>
|
||||
|
||||
// 访问子组件实例
|
||||
console.log(this.$refs.schoolInfoRef); // 输出: SchoolInfo组件实例
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
## 三、ref 的核心特性
|
||||
|
||||
### 1. 绑定目标类型
|
||||
|
||||
| 绑定目标 | 获取内容 | 使用场景 |
|
||||
| --------- | ---------------- | ----------------------- |
|
||||
| DOM元素 | 原生DOM节点 | 直接操作DOM |
|
||||
| 组件 | 组件实例 | 调用子组件方法/访问数据 |
|
||||
| v-for元素 | DOM数组/组件数组 | 操作列表元素 |
|
||||
|
||||
### 2. 生命周期时机
|
||||
|
||||
- **创建**:在组件 `mounted` 钩子之后可用
|
||||
- **更新**:响应式更新后自动同步
|
||||
- **销毁**:组件销毁时自动解除引用
|
||||
|
||||
### 3. 访问方式
|
||||
|
||||
通过组件实例的 `$refs` 对象访问:
|
||||
```javascript
|
||||
this.$refs.refName
|
||||
```
|
||||
|
||||
## 四、最佳实践
|
||||
|
||||
### 1. 命名规范
|
||||
- 使用 camelCase 命名(如 `schoolInfoRef`)
|
||||
- 避免使用保留字或Vue内置名称
|
||||
- 保持命名语义化(如 `formRef`, `tableRef`)
|
||||
|
||||
### 2. 安全访问模式
|
||||
```javascript
|
||||
methods: {
|
||||
submitForm() {
|
||||
// 先检查是否存在
|
||||
if (this.$refs.formRef) {
|
||||
this.$refs.formRef.validate();
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. 动态ref(Vue 2.6+)
|
||||
```html
|
||||
<div v-for="item in list" :ref="`item_${item.id}`"></div>
|
||||
|
||||
<script>
|
||||
methods: {
|
||||
getItemRef(id) {
|
||||
return this.$refs[`item_${id}`];
|
||||
}
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
## 五、高级用法
|
||||
|
||||
### 1. 组件通信
|
||||
```javascript
|
||||
// 父组件
|
||||
this.$refs.childComp.doSomething();
|
||||
|
||||
// 子组件 SchoolInfo.vue
|
||||
export default {
|
||||
methods: {
|
||||
doSomething() {
|
||||
// 子组件暴露的方法
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. 表单验证示例
|
||||
```html
|
||||
<template>
|
||||
<form ref="formRef">
|
||||
<input v-model="form.name" required>
|
||||
<button @click.prevent="validate">提交</button>
|
||||
</form>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
methods: {
|
||||
validate() {
|
||||
const form = this.$refs.formRef;
|
||||
if (form.checkValidity()) {
|
||||
// 表单验证通过
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
### 3. 结合第三方库
|
||||
```javascript
|
||||
mounted() {
|
||||
// 使用ref初始化第三方库
|
||||
this.chart = new Chart(this.$refs.chartCanvas, {
|
||||
// 配置项
|
||||
});
|
||||
},
|
||||
beforeDestroy() {
|
||||
// 清理工作
|
||||
this.chart.destroy();
|
||||
}
|
||||
```
|
||||
|
||||
## 六、注意事项
|
||||
|
||||
1. **响应式限制**:
|
||||
- `$refs` 不是响应式的
|
||||
- 避免在模板或计算属性中使用
|
||||
|
||||
2. **执行时机**:
|
||||
- 在 `mounted` 之前访问会是 `undefined`
|
||||
- 更新后需要等待 `$nextTick` 获取最新引用
|
||||
|
||||
3. **过度使用问题**:
|
||||
- 优先考虑 props/events 通信
|
||||
- 避免形成紧密耦合的组件关系
|
||||
|
||||
4. **与 Vue3 的区别**:
|
||||
- Vue3 中 ref 需要从 `vue` 导入
|
||||
- 组合式 API 中使用 `ref()` 函数创建响应式引用
|
|
@ -0,0 +1,4 @@
|
|||
const { defineConfig } = require('@vue/cli-service')
|
||||
module.exports = defineConfig({
|
||||
transpileDependencies: true
|
||||
})
|
|
@ -0,0 +1,9 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Document</title>
|
||||
</head>
|
||||
<body></body>
|
||||
</html>
|
Loading…
Reference in New Issue