在 Vue 3 中读取数据的方法包括:模板中使用响应性数据;使用 ref 获取元素引用;使用 computed 计算属性;使用 watch 监听响应性数据变更;使用 provide/inject 传递数据。

Vue 3 中如何读取数据
在 Vue 3 中,有以下几种方法可以读取数据:
1. 模板中使用响应性数据:
通过使用插值语法 {{}},可以在模板中访问响应性数据。
立即学习“前端免费学习笔记(深入)”;
<code class="html"><template>
<p>{{ message }}</p>
</template>
<script>
export default {
data() {
return {
message: 'Hello Vue 3!'
}
}
}
</script></code>2. 使用 ref 获取元素引用:
ref 属性允许访问 DOM 元素或子组件的引用。
<code class="html"><template>
<input ref="input" />
</template>
<script>
export default {
mounted() {
// 在挂载后获取 input 元素的引用
console.log(this.$refs.input);
}
}
</script></code>3. 使用 computed 计算属性:
computed 属性是一种只读属性,用于根据其他响应性数据计算值。
<code class="html"><template>
<p>{{ fullName }}</p>
</template>
<script>
export default {
data() {
return {
firstName: 'John',
lastName: 'Doe'
}
},
computed: {
fullName() {
return `${this.firstName} ${this.lastName}`;
}
}
}
</script></code>4. 使用 watch 监听响应性数据变更:
watch 选项允许监听响应性数据的变化并执行回调函数。
<code class="html"><template>
<input v-model="message" />
</template>
<script>
export default {
data() {
return {
message: 'Hello Vue 3!'
}
},
watch: {
message(newVal, oldVal) {
console.log('Message changed:', newVal, oldVal);
}
}
}
</script></code>5. 使用 provide/inject 传递数据:
provide 和 inject 选项用于在祖先和后代组件之间传递数据。
<code class="html"><!-- 祖先组件 -->
<template>
<component-a>
<component-b />
</component-a>
</template>
<script>
export default {
provide() {
return {
sharedData: 'This data is shared between components'
}
}
}
</script>
<!-- 后代组件 -->
<template>
<p>{{ sharedData }}</p>
</template>
<script>
export default {
inject: ['sharedData']
}
</script></code>以上就是vue3怎么读数据的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号