vue3抽离封装
船长在船上 人气:0vue3的抽离封装方法:
vue3中的任何一个组合式api都可以单独抽离出去在另一个文件,最后只需要回归到setup()中即可。
1.新建公共utils/publicModule文件
// 公共的数据和方法 import { reactive } from "vue" const publicModule = ()=>{ const res = reactive({ name:"马腾腾", age:50, company:"百度" }) return res } export default publicModule
2.vue组件页面中引入使用
注意const res = publicModule()这里的值获取,容易写错获取不到;
点击handleClick事件修改引入的值
<template> <div> <div class="main"> <div>vue3抽离封装:</div> <div>name:{{res.name}}</div> <div>age:{{res.age}}</div> <div>company:{{res.company}}</div> <el-button type="primary" block @click="handleClick">修改name</el-button> </div> </div> </template> <script> import publicModule from "../../utils/publicModule" export default { setup() { const res = publicModule(); console.log(res,"vue3抽离封装"); function handleClick(){ res.name = "马云" } return { res, handleClick }; } }; </script>
或者使用toRefs
<template> <div> <div class="main"> <div>vue3抽离封装:</div> <!-- toRefs --> <div>name:{{name}}</div> <div>age:{{age}}</div> <div>company:{{company}}</div> <el-button type="primary" block @click="handleClick">修改name</el-button> </div> </div> </template> <script> import publicModule from "../../utils/publicModule" import {toRefs} from "vue" export default { setup() { const res = publicModule(); console.log(res,"vue3抽离封装"); function handleClick(){ res.name = "马云" } return { ...toRefs(res), handleClick }; } }; </script>
加载全部内容