卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章75178本站已运行4311

vue3怎么读数据

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

vue3怎么读数据

Vue 3 中如何读取数据

在 Vue 3 中,有以下几种方法可以读取数据:

1. 模板中使用响应性数据:

通过使用插值语法 {{}},可以在模板中访问响应性数据。

立即学习“前端免费学习笔记(深入)”;

<template><p>{{ message }}</p>
</template><script>
export default {
  data() {
    return {
      message: 'Hello Vue 3!'
    }
  }
}
</script>

2. 使用 ref 获取元素引用:

ref 属性允许访问 DOM 元素或子组件的引用。

<template><input ref="input"></template><script>
export default {
  mounted() {
    // 在挂载后获取 input 元素的引用
    console.log(this.$refs.input);
  }
}
</script>

3. 使用 computed 计算属性:

computed 属性是一种只读属性,用于根据其他响应性数据计算值。

<template><p>{{ fullName }}</p>
</template><script>
export default {
  data() {
    return {
      firstName: 'John',
      lastName: 'Doe'
    }
  },
  computed: {
    fullName() {
      return `${this.firstName} ${this.lastName}`;
    }
  }
}
</script>

4. 使用 watch 监听响应性数据变更:

watch 选项允许监听响应性数据的变化并执行回调函数。

<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>

5. 使用 provide/inject 传递数据:

provide 和 inject 选项用于在祖先和后代组件之间传递数据。

<!-- 祖先组件 -->
<template><component-a><component-b></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>
卓越飞翔博客
上一篇: vue3怎么用 element
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏