vue3 inject 计算属性
时间: 2024-01-26 12:13:47 浏览: 124
在Vue 3中,你可以使用`provide`和`inject`来实现计算属性的响应式。下面是一个示例:
```javascript
import { provide, inject, computed } from 'vue';
const app = createApp();
app.component('todo-list', {
setup() {
const todos = ['todo1', 'todo2', 'todo3'];
// 使用computed创建计算属性
const todoLength = computed(() => todos.length);
// 使用provide提供计算属性
provide('todoLength', todoLength);
return {
todos
};
},
template: `
<div>
<ul>
<li v-for="todo in todos" :key="todo">{{ todo }}</li>
</ul>
<todo-list-statistics></todo-list-statistics>
</div>
`
});
app.component('todo-list-statistics', {
setup() {
// 使用inject获取计算属性
const todoLength = inject('todoLength');
return {
todoLength
};
},
created() {
console.log(`Injected property: ${this.todoLength.value}`);
},
template: `
<div>
<p>Injected property: {{ todoLength.value }}</p>
</div>
`
});
app.mount('#app');
```
在上面的示例中,`todo-list`组件使用`provide`提供了一个名为`todoLength`的计算属性,`todo-list-statistics`组件使用`inject`来获取这个计算属性。在`todo-list-statistics`组件的`created`钩子函数中,我们打印了注入的计算属性的值。
阅读全文
相关推荐


















