我希望从Options切换到Composition,并使用composables代替mixin。到目前为止,我一直在使用具有以下计算属性的全局混合:
// globalMixin.js
computed: {
myAlert() {
return this.$refs.myAlertDiv;
}
}然后,我在创建应用程序时使用了这个混合器:
// MyApp.js
const MyApp = {
mixins: [globalMixin]
...
}myAlert成为MyApp的计算属性,我可以使用它而不直接在MyApp属性中声明。
现在,我想要实现与可组合性相同的结果,假设我有一个导入可组合的组件:
// App.vue
<script setup>
import { useGlobalComposable} from './globalComposable.js';
const globalComposable = useGlobalComposable();
onMounted(() => {
// should work without declaring myAlert inside App.vue
console.log(globalComposable.myAlert);
})
...
</script>做得到吗?如果是这样的话,我应该如何在可组合的内部声明myAlert模板ref?
发布于 2022-11-07 11:02:40
useGlobalComposable函数应该返回myAlert,如下所示:
const useGlobalComposable = function() {
const myAlertDiv = ....
const myAlert = computed(() => {
return myAlertDiv;
});
return {myAlert}
}然后可以在安装块中声明myAlert。
const { myAlert } = useComposable();
return { myAlert }注意,来自this.$refs的mixin不会直接与复合API一起工作。如果创建组件,则可以使用this访问组件属性和方法。
这里有一篇关于using refs with Composition API的好文章。
在setup中使用可组合的非常简单的工作示例
const { ref, reactive, createApp } = Vue;
const useComposable = function() {
const test = ref(1);
return { test };
}
const App = {
setup() {
const { test } = useComposable();
return { test }
}
}
const app = createApp(App)
app.mount('#app')<div id="app">
<div>Test: {{ test }}</div>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
https://stackoverflow.com/questions/74321345
复制相似问题