vue2父组件
<template>
<div>
<input type="text" v-model="val" />
<button @click="addClick(val)">添加</button>
<ListItem></ListItem>
<div v-for="item in lists" :key="item">
<li>{{ item }}</li>
</div>
</div>
</template>
<script>
import ListItem from "@/components/ListItem";
import { computed } from "vue";
export default {
components: {
ListItem,
},
provide() {
return {
todoLength: computed(() => this.lists.length),
};
},
data() {
return {
lists: [1, 2, 3],
val: "",
};
},
methods: {
addClick(val) {
this.lists.push(val);
},
},
};
</script>
vue2子组件
<template>
<div>
<div>todoLength{{ todoLength }}</div>
</div>
</template>
<script>
export default {
name: "ListItem",
inject: ["todoLength"],
};
</script>
vue3父组件
<template>
<div>
<ul>
<li v-for="(item, index) in lists" :key="index">{{ item }}</li>
</ul>
<TodoListStatistics2></TodoListStatistics2>
</div>
</template>
<script>
import { ref, provide } from "vue";
import TodoListStatistics2 from "./TodoListStatistics2.vue";
export default {
components: { TodoListStatistics2 },
setup() {
const lists = ref([1, 2, 3]);
provide("listslen", lists);
const addList = (val) => {
lists.value.push(val);
};
provide("addList", addList);
return {
lists,
};
},
};
</script>
vue3子组件
<template>
<div>
<h3>lists的长度:{{ listslen.length }}</h3>
<input type="text" v-model="val" />
<button @click="addList(val)">添加</button>
</div>
</template>
<script>
import { inject } from "vue";
export default {
setup() {
const listslen = inject("listslen");
const addList = inject("addList");
return { listslen, addList };
},
data() {
return {
val: "",
};
},
};
</script>
vue3官方详细使用provide inject地址:(https://v3.cn.vuejs.org/guide/composition-api-provide-inject.html#%E4%BD%BF%E7%94%A8-provide)
网友评论