//子页面 Child.vue <template> <div>子页面计数:{{ count }}</div> </template> <script> import { ref } from "vue"; export default { name: "Child", setup() { const count = ref(0); const add = () => { count.value++; }; const addCustom = (value) => { count.value += value; }; return { count, add, addCustom, }; }, }; </script> <style lang="scss" scoped> </style>
// 父页面 Index.vue <template> <div> <Child ref="child"></Child> <br /> 父页面按钮:<button @click="handleAdd">点击+1</button> <br /> 父页面按钮:<button @click="handleAddCustom">(添加自定义数值)点击+10</button> </div> </template> <script> import { ref } from "vue"; import Child from "./Child"; export default { name: "Parent", components: { Child, }, setup() { const child = ref(); const handleAdd = () => { child.value.add(); }; const handleAddCustom = () => { child.value.addCustom(10); }; return { child, handleAdd, handleAddCustom }; }, }; </script> <style lang="scss" scoped> </style>
上面展示的是我的代码实现,代码逻辑是我计数,但是当把这个组件以子组件的方式引进去的时候,我想直接通过调用子组件的方法去实现数字的累加。
上图为界面。
转载链接:https://www.jianshu.com/p/846e1157b96b