1、問題1:如何在父組件中去調(diào)用子組件的方法
在使用vue3.0的時(shí)候,需要去調(diào)取子組件的方法去快速的解決需求,類似于在Vue2.x中的this.$refs去操作虛擬dom元素的方法,但是在Vue3.0中是沒有this指向的,那么解決辦法就是先將ref的值定義一個(gè)對(duì)象,其value值再指向是子組件component。
父組件:
<script>
// import Dialog from "@/components/dialog/dialog.vue";
import { reactive, ref, defineComponent } from "@vue/composition-api";
import Dialog from "../../components/dialog/dialog.vue";
export default defineComponent({
components: {
Dialog,
},
setup(props, { root }) {
const dialog = ref(null);
// 編輯操作
const handleEdit = (index, row) => {
dialog.value.open(row);
};
}
子組件:
<script>
import { reactive, ref, defineComponent } from "@vue/composition-api";
export default defineComponent({
setup(props, { root }) {
const dialogTableVisible = ref(false);
// 方法
const open = () => {
dialogTableVisible.value = true;
};
return {
dialogTableVisible,
open
};
},
});
</script>
上面展示的是我的部分的代碼實(shí)現(xiàn),代碼邏輯是我將一個(gè)公共彈窗組件提出來,但是當(dāng)把這個(gè)組件以子組件的方式引進(jìn)去的時(shí)候,我想直接通過調(diào)用子組件的方法去實(shí)現(xiàn)彈出框的打開關(guān)閉。
截圖.png
通過使用上面的方法,成功解決了這個(gè)問題。
問題2、如何在Vue的原型對(duì)象上全局的添加自定義方法
導(dǎo)入的elementUI的消息提示框:
- 新建一個(gè)utils文件目錄,文件目錄下添加一個(gè)global.js文件,然后這里面可以寫一些自己的方法了
import { MessageBox, Message } from 'element-ui';
export default {
install(Vue,options){
Vue.prototype.remove = function(params){
MessageBox.confirm(params.content, params.tips || "提示", {
confirmButtonText: "刪除",
cancelButtonText: "取消",
center:true,
type: "error",
})
.then(() => {
params.fn && params.fn(params.id)
// if(params.fn){ params.fn()}
Message.success('刪除成功!')
})
.catch(() => {
Message.error('已取消刪除!')
});
}
}
}
上面的代碼,params是從外面?zhèn)鬟M(jìn)來的參數(shù),這個(gè)里面可以把值或者一些方法傳進(jìn)來都是可以的。
- main.js引入文件
import global from "@/utils/global.js";
Vue.use(global);
- 調(diào)用部分的代碼
import { reactive, ref, defineComponent } from "@vue/composition-api";
import Dialog from "../../components/dialog/dialog.vue";
export default defineComponent({
components: {
Dialog,
},
setup(props, { root }) {
// 行刪除
const handleDelete = (index, row) => {
root.remove({
content: "是否刪除當(dāng)前數(shù)據(jù)?",
fn:handleRefresh,
id:'012121231'
});
};
// 刪除后刷新表格數(shù)據(jù)
const handleRefresh = (value) => {
console.log('刪除后的數(shù)據(jù)....',value);
};
return {
handleDelete,
};
},
});
之后就不需要在每個(gè)組件內(nèi)部寫一段重復(fù)冗余的代碼了,直接調(diào)用全局方法,然后把需要傳入的參數(shù)帶進(jìn)去,就解決問題了。
截圖.png