Van*_*anz 4 javascript vue.js vuejs3 vue-composition-api
我在reactive()中有一个帖子数组,我希望它在Mounted上更新。
我怎样才能做到这一点?
模板:
<q-card>
<board-item-list :items="items" v-if="items.length" />
<board-empty v-else />
</q-card>
Run Code Online (Sandbox Code Playgroud)
脚本
import { reactive, onMounted } from "vue";
import { posts } from "./fake-data.js";
export default {
setup() {
let items = reactive([]);
...
onMounted(() => {
// to fill the items with posts.
items.values = posts; // I tried this not working
items = posts; //I tried this not working
console.log(items);
});
...
return {
...
items,
};
},
};
Run Code Online (Sandbox Code Playgroud)
Bou*_*him 11
尝试使用ref而不是reactive或定义items为反应状态的嵌套字段,例如:
import { reactive, onMounted } from "vue";
import { posts } from "./fake-data.js";
export default {
setup() {
let state= reactive({items:[]});
...
onMounted(() => {
state.items = posts;
console.log(state.items);
});
...
return {
...
state,
};
},
};
Run Code Online (Sandbox Code Playgroud)
在模板中:
<q-card>
<board-item-list :items="state.items" v-if="state.items.length" />
<board-empty v-else />
</q-card>
Run Code Online (Sandbox Code Playgroud)
state如果你想在模板中删除你可以使用toRefs:
import { reactive, onMounted,toRefs } from "vue";
import { posts } from "./fake-data.js";
export default {
setup() {
let state= reactive({items:[]});
...
onMounted(() => {
state.items = posts;
console.log(state.items);
});
...
return {
...toRefs(state),//you should keep the 3 dots
};
},
};
Run Code Online (Sandbox Code Playgroud)